package com.cartrack.cartrackble

import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.cartrack.blesdk.ctg.*
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private var test: PermissionManager? = null
    private var bleTerminal: BleTerminal? = null
    private var progressDialog: ProgressDialog? = null

    //sample vendorId and apiKey
    private val apiKey: String = "97084cbb-deaf-471c-8e9d-b920f0f8b798"
    private val vendorId: String = "227020"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val lastUsedTerminalId = getSharedPreferences().getString(LAST_USED_TERMINAL_ID, "EE004778")
        et_terminal_id.setText(lastUsedTerminalId)

        progressDialog = ProgressDialog(this)
        test = PermissionManager(this)
        test?.requestPermission()

        // Configure BleService with vendorId and apiKey on application
        BleService.configure(this, vendorId, apiKey)

        btn_disconnect.setOnClickListener { bleTerminal?.disconnect() }
        btn_connect.setOnClickListener {
            getSharedPreferences().set(LAST_USED_TERMINAL_ID, et_terminal_id.text.toString())
            if (isEnabled()) {
                progressDialog?.showProgress()
                connect(et_terminal_id.text.toString())
            } else checkBleState()
        }

        btn_get_vehicle_state.setOnClickListener {
            progressDialog?.showProgress()
            bleTerminal?.sendAction(BleAction.GET_LOCK_STATE)
        }

        btn_lock.setOnClickListener {
            progressDialog?.showProgress()
            bleTerminal?.sendAction(BleAction.LOCK)
        }
        btn_unlock.setOnClickListener {
            progressDialog?.showProgress()
            bleTerminal?.sendAction(BleAction.UNLOCK)
        }

        btn_action_one.setOnClickListener {
            progressDialog?.showProgress()
            bleTerminal?.sendAction(BleAction.HEADLIGHT)
        }
        btn_action_two.setOnClickListener {
            progressDialog?.showProgress()
            bleTerminal?.sendAction(BleAction.HORN)
        }
    }

    override fun onPause() {
        bleTerminal?.disconnect()
        disableAction()
        super.onPause()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            REQUEST_ON_CONNECT -> {
                if (resultCode == Activity.RESULT_OK) {
                    connect(et_terminal_id.text.toString())
                }
            }
        }

        super.onActivityResult(requestCode, resultCode, data)
    }

    private fun connect(terminalId: String) {
        bleTerminal = BleService.getTerminal(terminalId)
        bleTerminal?.bleListener = bleListener
        bleTerminal?.prefetchAuthKey(
            onSuccess = {
                bleTerminal?.scanAndConnectToPeripheral()
            },
            onError = {
                progressDialog?.dismissProgress()
                Snackbar.make(root_view, "Unable to get terminal key", Snackbar.LENGTH_SHORT).show()
            }
        )
    }

    private fun checkBleState() {
        val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled) {
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableBtIntent, REQUEST_ON_CONNECT)
        }
    }

    private fun isEnabled(): Boolean {
        val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        return bluetoothAdapter.isEnabled
    }

    private fun enableAction() {
        btn_connect.isEnabled = false
        btn_unlock.isEnabled = true
        btn_lock.isEnabled = true
        btn_disconnect.isEnabled = true
        btn_action_one.isEnabled = true
        btn_action_two.isEnabled = true
        btn_get_vehicle_state.isEnabled = true
    }

    private fun disableAction() {
        btn_connect.isEnabled = true
        btn_unlock.isEnabled = false
        btn_lock.isEnabled = false
        btn_disconnect.isEnabled = false
        btn_action_one.isEnabled = false
        btn_action_two.isEnabled = false
        btn_get_vehicle_state.isEnabled = false
    }

    private val bleListener = object : BleListener {
        override fun onTerminalConnected(terminal: BleTerminal) {
            Snackbar.make(
                root_view,
                "${terminal.terminalId} Connected",
                Snackbar.LENGTH_SHORT
            ).show()

            enableAction()
            progressDialog?.dismissProgress()
        }

        override fun onTerminalConnectionFailed(
            terminal: BleTerminal,
            status: BleConnectionStatus
        ) {
            Snackbar.make(
                root_view,
                "${status.name} for device (${et_terminal_id.text})",
                Snackbar.LENGTH_SHORT
            ).show()
            disableAction()
            progressDialog?.dismissProgress()
        }

        override fun onTerminalCommandResult(action: BleAction, result: BleActionResult) {
            if (action != BleAction.GET_LOCK_STATE) {
                val message =
                    if (result == BleActionResult.SUCCESS) "Success executing $action"
                    else "Failed executing $action"

                Snackbar.make(
                    root_view,
                    message,
                    Snackbar.LENGTH_SHORT
                ).show()
            }
            tv_lock_state.text = "Current State: ${bleTerminal?.getLockState().toString()}"
            progressDialog?.dismissProgress()
        }

        override fun onTerminalDisconnected(terminal: BleTerminal) {
            Snackbar.make(
                root_view,
                "${terminal.terminalId} Disconnected",
                Snackbar.LENGTH_SHORT
            ).show()
            disableAction()
            tv_lock_state.text = "Current State: ${bleTerminal?.getLockState().toString()}"
            progressDialog?.dismissProgress()
        }

        override fun onGetAuthKey(terminal: BleTerminal, result: GetAuthKeyResult) = Unit

        override fun onSignalStrength(strength: BleSignalStrength) {
            Snackbar.make(
                root_view,
                strength.name,
                Snackbar.LENGTH_SHORT
            ).show()
        }
    }

    private fun getSharedPreferences(): PreferenceManager {
        return LocalPreferenceManager(
            getSharedPreferences(
                "com.cartrack.getgosample.prefs",
                Activity.MODE_PRIVATE
            )
        )
    }

    companion object {
        private const val REQUEST_ON_CONNECT = 101
        private const val LAST_USED_TERMINAL_ID = "lastUsedTerminalId"
    }
}
