package com.casic.electric.detector.view

import android.os.Bundle
import android.os.CountDownTimer
import com.casic.electric.detector.R
import com.casic.electric.detector.utils.LocaleConstant
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.extensions.navigatePageTo
import com.pengxh.kt.lite.utils.SaveKeyValues
import pub.devrel.easypermissions.EasyPermissions

class PermissionActivity : KotlinBaseActivity(), EasyPermissions.PermissionCallbacks {

    private val isFirstEnter = SaveKeyValues.getValue("isFirstEnter", true) as Boolean
    private val countDownTimer = object : CountDownTimer(2000, 500) {
        override fun onFinish() {
            navigatePageTo<LoginActivity>()
            finish()
        }

        override fun onTick(millisUntilFinished: Long) {

        }
    }

    override fun initData(savedInstanceState: Bundle?) {
        EasyPermissions.requestPermissions(
            this, "${resources.getString(R.string.app_name)}需要获取必要权限",
            LocaleConstant.PERMISSIONS_CODE, *LocaleConstant.USER_PERMISSIONS
        )
    }

    override fun initEvent() {

    }

    override fun initLayoutView(): Int = R.layout.activity_permssion

    override fun observeRequestState() {

    }

    override fun setupTopBarLayout() {
        ImmersionBar.with(this).statusBarDarkFont(false).init()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<out String>, grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        if (isFirstEnter) {
            SaveKeyValues.putValue("isFirstEnter", false)
            navigatePageTo<LoginActivity>()
            finish()
        } else {
            countDownTimer.start()
        }
    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {

    }

    override fun onDestroy() {
        super.onDestroy()
        countDownTimer.cancel()
    }
}