package com.sambath.kunkhmer.base

import android.content.Intent
import android.os.Bundle
import com.sambath.kunkhmer.app.App
import com.sambath.kunkhmer.screen.login.LoginActivity
import com.sambath.kunkhmer.util.Const
import com.sambath.kunkhmer.util.Const.Companion.DEFAULT_LOGOUT_TIME
import com.sambath.kunkhmer.util.LogOutTimerUtil

abstract class AutoLogoutBaseActivity(private val logoutTime: Int = DEFAULT_LOGOUT_TIME) : BaseActivity() {
    private val sharePref = App.injectPrefHelper()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        LogOutTimerUtil.isUserTimedOutLiveData
            .observe(this, { isUserTimedOut ->
                if (isUserTimedOut)
                    logout()
            })
    }

    override fun onResume() {
        super.onResume()
        if (LogOutTimerUtil.isUserTimedOutLiveData.value == false) {
            Const.LOGOUT_TIME = logoutTime
            LogOutTimerUtil.resetLogoutTimer(null, null)
        }
    }

//    override fun onUserInteraction() {
//        super.onUserInteraction()
//        LogOutTimerUtil.resetLogoutTimer(null, null)
//    }

    private fun logout() {
        LogOutTimerUtil.isUserTimedOutLiveData.postValue(false)     // Reset timeout flag for background mode
        sharePref.logout()

        val intent = Intent(this, LoginActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        startActivity(intent)
        finish()
    }
}