package com.mytatvarnsdk

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.ViewModelProviders
import cgmblelib.Enum.enumUnBind
import cgmblelib.Enum.enumUnBind.UNBIND_RESET
import cgmblelib.ble.BleService
import cgmblelib.ble.gattcallback.GattTool
import cgmblelib.ble.gattcallback.ManageGattCallback
import cgmblelib.ble.reconnectManagament.ReconnectManagement
import cgmblelib.custom.livedata.scan.PocDeviceAndRssi
import cgmblelib.database.repository.RepositoryDevice
import cgmblelib.utils.MyLog
import cgmblelib.utils.Tool
import com.mytatvarnsdk.base.BaseBleActivity
import com.mytatvarnsdk.model.MainActivityModel
import com.mytatvarnsdk.myView.RtlViewPager
import com.mytatvarnsdk.myView.dialog.AlarmDialogManagement
import com.mytatvarnsdk.myView.dialog.DialogType
import com.mytatvarnsdk.myView.dialog.WarnDialogUtils
import com.mytatvarnsdk.myView.progress.ProgressManagement
import com.mytatvarnsdk.myView.progress.ProgressType
import com.mytatvarnsdk.utils.CGMTool

class MainActivity : BaseBleActivity() {

  /**
   * 强制关闭 resultCode
   */

  val RESPONSE_UNBIND_FORCE: Int = 320

  val RESPONSE_UNBIND: Int = 321

  /**
   * 访问界面的RequestCode
   */
  val REQUEST_ACTIVITY: Int = 123

  /**
   * model数据库
   */
  private lateinit var mModel: MainActivityModel

  /**
   * 切换页面
   */
  private lateinit var mViewPager: RtlViewPager

  /**
   * 是否通知默认开启状态
   */
  private val notificationEnable = true

  /**
   * 正在进行数据拉取的阶段
   */
  var isInPullData: Boolean = false
    private set

  private var alarmImg: ImageView? = null

  protected override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    /*数据绑定*/
    mModel = ViewModelProviders.of(this).get(MainActivityModel::class.java)
  }

  protected override fun onResume() {
    super.onResume()
    isInPullData = false
    BleService.startService(this)
  }

  protected override fun onNewIntent(intent: Intent) {
    super.onNewIntent(intent)
    val code = intent.getStringExtra("code")
  }

  protected override fun onPause() {
    super.onPause()
  }

  public override fun onPermissionRequestSuccess() {
    ReconnectManagement.getInstance().reconnect(ReconnectManagement.ReconnectState.STATE_SCAN_AGAIN)
  }

  public override fun scanStart() {
    if (mPocDevice != null && mPocDevice.isBound()) {
      ProgressManagement.getInstance().showWait(this, ProgressType.PROGRESSDIALOG_SCAN, null)
    }
  }

  public override fun scanIn(device: PocDeviceAndRssi?) {
    if (mPocDevice != null && mPocDevice.isBound()) {
      ProgressManagement.getInstance().showWait(this, ProgressType.PROGRESSDIALOG_SCAN, null)
    }
  }

  public override fun scanEnd() {
    ProgressManagement.getInstance().dismissWait(this)
  }

  public override fun bluetoothStateOFF() {
    ProgressManagement.getInstance().dismissWait(this)
    showShortToast(R.string.please_open_bluetooth)
    isInPullData = false
  }

  public override fun failGPS() {
    ProgressManagement.getInstance().dismissWait(this)
    warn_gpsFail()
    isInPullData = false
  }

  public override fun failLocal() {
    ProgressManagement.getInstance().dismissWait(this)
    requestPermission()
    isInPullData = false
  }

  public override fun bindFail() {
    ProgressManagement.getInstance().dismissWait(this)
  }

  public override fun disconnect() {
    ProgressManagement.getInstance().dismissWait(this)
    showShortToast(R.string.bt_connect_fail)
  }

  public override fun disconnectForTimeout() {
    ProgressManagement.getInstance().dismissWait(this)
    showShortToast(R.string.bt_connect_fail)
  }

  public override fun checkFailForLowPower() {
    ProgressManagement.getInstance().dismissWait(this)
  }

  public override fun checkFailErrorTemperature() {
    ProgressManagement.getInstance().dismissWait(this)
  }

  public override fun pullStart() {
    isInPullData = true
  }

  public override fun pullIn() {
    isInPullData = true
  }

  public override fun pullEnd() {
    isInPullData = false
  }

  public override fun unbindReset() {
    ProgressManagement.getInstance().dismissWait(this)
    WarnDialogUtils.getInstance().dismissWarnDialog()
    unBind(enumUnBind.UNBIND_RESET)
  }

  public override fun unbindCommand() {
    ProgressManagement.getInstance().dismissWait(this)
    WarnDialogUtils.getInstance().dismissWarnDialog()
    unBind(enumUnBind.UNBIND_COMMAND)
  }

  public override fun onlineLost() {
    WarnDialogUtils.getInstance().dismissWarnDialog()
    showShortToast(R.string.online_lost)
  }

  protected override fun initViews() { //初始化 Fragment以及底部导航栏
    mViewPager = findViewById(R.id.container)
    //todo Ankit - need to review the code
  }

  protected override fun init() {
    this.device
    this.allGlucose
    this.latestGlucose
  }

  val isBind: Boolean
    get() {
      if (mPocDevice != null) {
        return mPocDevice.isBound()
      } else {
        return false
      }
    }


  fun leftTime(): String? {
    if (mPocDevice != null && mPocDevice.isBound() && mLatestPocGlucose != null) {
      return getResources().getString(
        R.string.left_cycle,
        CGMTool.getTitleShow(getApplicationContext(), mPocDevice, mLatestPocGlucose)
      )
    }
    return "-"
  }

  private fun switchImg(isShowItUi: Boolean) {
    if (isShowItUi && mViewPager.getCurrentItem() === Check_Sensor) {
      alarmImg!!.setImageResource(R.drawable.alarm_sound_shake_white)
    }
  }

  private val device: Unit
    /***
     * 获取设备数据
     */
    get() {
      mModel.getDevice().observe(this, { device ->
        mPocDevice = device
        isInPullData = false
        sureClose()
        if (mPocDevice == null || mPocDevice.isUnBind()) {
          showView(Check_Unbind)
        }
        showTitle()
      })
    }

  private val allGlucose: Unit
    /**
     * 获取所有血糖数据
     */
    get() {
      mModel.getAllGlucose().observe(this, { pocGlucoses -> mPocGlucoses = pocGlucoses })
    }

  private var lastTime: Long = 0

  private val latestGlucose: Unit
    /***
     * 获取最新的血糖数据
     */
    get() {
      mModel.getLatestGlucose().observe(this, { pocGlucose ->
        mLatestPocGlucose = pocGlucose
        if (mPocDevice != null && mPocDevice.isBoundAndConnect() && !isInPullData) {
          //避免一次血糖值触发两次
          if (System.currentTimeMillis() - lastTime > 1000) {
            AlarmDialogManagement.getInstance().showAlarmDialog(this, mLatestPocGlucose)
            lastTime = System.currentTimeMillis()
          }
        }
      })
    }

  /**
   * 开启或关闭传感器 -- 不一定是弹框
   *
   * @param isForce true,强制关闭 false,命令关闭
   */
  fun unBindTransmitter(isForce: Boolean) {
    if (isForce) {
      //强制解除绑定
      unBindForce()
    } else {
      //发送命令解除绑定
      if (mPocDevice != null) {
        ManageGattCallback.getInstance().unBindDevice(mPocDevice)
      }
    }
  }

  /**
   * 强制结束时修改数据
   */
  private fun unBindForce() {
    GattTool.unBindInDatabase(this, enumUnBind.UNBIND_FORCE)
  }

  /**
   * 存储空间判断
   * 若低于存储空间则弹框提示
   */
  fun storageJudge() {
    val appDir = Tool.getAppDir(this)
    if (appDir != null) {
      val available = Tool.getAvailableSize(appDir)
    }
  }

  public override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
      ProgressManagement.getInstance().dismissWait(this)
      WarnDialogUtils.getInstance().dismissWarnDialog()
      exit()
      return true
    }
    return super.onKeyDown(keyCode, event)
  }

  protected override fun setView(): Int {
    return R.layout.activity_main
  }

  /**
   * last click time
   */
  private var clickTime: Long = 0

  /**
   * exit APP 退出APP
   */
  private fun exit() {
    if ((System.currentTimeMillis() - clickTime) > 2000) {
      clickTime = System.currentTimeMillis()
    } else {
      this.finish()
    }
  }

  /**
   * 发射器与APP解除绑定后，需要弹框
   *
   * @param unBind 解除绑定的类型
   */
  private fun unBind(unBind: enumUnBind) {
    MyLog.i("接触绑定的类型 " + unBind.getType())
    ProgressManagement.getInstance().dismissWait(this)
    val warnDialogType: Int
    when (unBind) {
      enumUnBind.UNBIND_RESET -> warnDialogType = DialogType.TYPE_UNBIND
      else -> warnDialogType = DialogType.TYPE_MONITORING_END
    }

    WarnDialogUtils.getInstance().showWarnDialog(this, warnDialogType, { dialog, which ->
      WarnDialogUtils.getInstance().dismissWarnDialog()
      confirmSureClose()
      showView(Check_Unbind)
    })
  }

  /**
   * 确认是否进行关闭确认
   */
  private fun sureClose() {
    if (mPocDevice != null && !mPocDevice.isBound() && mPocDevice.getSureClose() === 0) {
      when (mPocDevice.getUnBind()) {
        UNBIND_RESET -> unBind(enumUnBind.UNBIND_RESET)
        else -> {}
      }
    }
  }

  /**
   * 是否确认关闭
   */
  fun confirmSureClose() {
    if (mPocDevice != null) {
      mPocDevice.setSureClose(1)
      RepositoryDevice.getInstance(this).updateDevice(mPocDevice)
    }
  }

  protected override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == REQUEST_ACTIVITY) {
      if (resultCode == RESPONSE_UNBIND_FORCE) {
        unBindTransmitter(true)
      } else if (resultCode == RESPONSE_UNBIND) {
        unBindTransmitter(false)
      }
    }
  }

  public override fun onClick(v: View) {
    if (v.getId() == R.id.iv_alert_type) {
      if (mPocDevice != null && mPocDevice.isBound()) {
      }
    }
  }

  fun showView(checkedPosition: Int) {
    if (mViewPager.getVisibility() === View.INVISIBLE) {
      mViewPager.setVisibility(View.VISIBLE)
    }
    if (mViewPager.getCurrentItem() === checkedPosition || checkedPosition == -1) {
      return
    }
    mViewPager.setCurrentItem(checkedPosition)
    (findViewById(R.id.btnLeft) as ImageView).setImageResource(R.drawable.home_menu)
    showTitle()
  }

  private fun showTitle() {
    //todo Ankit - Review code
  }

  companion object {
    var Check_Sensor: Int = 0
    var Check_Unbind: Int = 1
    var Check_CountDown: Int = 2
  }
}
