package com.dlc.exam.ui.common

import android.os.Handler
import android.os.Looper
import android.os.Message
import androidx.viewbinding.ViewBinding
import com.dlc.exam.ExamApp
import com.dlc.exam.common.CommonUtils
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>() {

    override fun onResume() {
        super.onResume()
        mCounter = 0
        mCountDownHandler.sendEmptyMessage(WHAT_COUNT_DOWN)
    }

    override fun onStop() {
        mCounter = 0
        mCountDownHandler.removeMessages(WHAT_COUNT_DOWN)
        super.onStop()
    }

    override fun onUserInteraction() {
        mCounter = 0
        mCountDownHandler.removeMessages(WHAT_COUNT_DOWN)
        mCountDownHandler.sendEmptyMessage(WHAT_COUNT_DOWN)
    }

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

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

                        CommonUtils.restartApp(applicationContext)
                    }
                } 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
    }



}