package com.dlc.chemical.ui.common

import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.os.Message
import androidx.viewbinding.ViewBinding
import com.dlc.chemical.ChemicalApp
import com.dlc.chemical.ui.MainActivity
import com.rc.core.ui.activity.RcBaseActivity
import com.rc.httpcore.HttpClient
import com.rc.httpcore.client.ApiRepository

/**
 * info
 *
 * @author ReiChin_
 */
abstract class BaseCountDownActivity<VB : ViewBinding> : RcBaseActivity<VB>() {

    protected fun startCountDown() {
        mCounter = 0
        mCountDownHandler.removeMessages(WHAT_COUNT_DOWN)
        if (null != ChemicalApp.sLearnLoginVo) {
            mCountDownHandler.sendEmptyMessage(WHAT_COUNT_DOWN)
        }
    }

    protected fun stopCountDown() {
        mCounter = 0
        mCountDownHandler.removeMessages(WHAT_COUNT_DOWN)
    }

    override fun onResume() {
        super.onResume()
        startCountDown()
    }

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

    override fun onDestroy() {
        mCountDownHandler.removeCallbacksAndMessages(null)
        super.onDestroy()
    }

    override fun onUserInteraction() {
        startCountDown()
    }

    private val mCountDownHandler = object : Handler(Looper.getMainLooper()) {

        override fun handleMessage(msg: Message) {
            if (WHAT_COUNT_DOWN == msg.what) {
                val countDown = MAX_TIME - mCounter
                if (isDestroyed) return
                if (countDown <= 0) {
                    callLogoutApi {
                        ChemicalApp.sLearnLoginVo = null
                        HttpClient.token = null

                        startActivity(Intent(this@BaseCountDownActivity, MainActivity::class.java))
                    }
                } else {
                    sendEmptyMessageDelayed(WHAT_COUNT_DOWN, 1000)
                }
                mCounter++
            }
        }
    }

    protected fun callLogoutApi(callback: ((success: Boolean) -> Unit)? = null) {
        showLoading("退出中...")
        val disposable = ApiRepository.loginOut()
            .subscribe({
                dismissLoading()
                callback?.invoke(true)
            }, {
                dismissLoading()
                callback?.invoke(false)
            })
        addDisposable(disposable)
    }

    private var mCounter = 0

    companion object {
        private const val MAX_TIME = 180

        private const val WHAT_COUNT_DOWN = 1
    }

}