package com.doverfuelingsolutions.issp.view.util

import android.app.Activity
import androidx.core.os.bundleOf
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.api.SystemApi
import com.doverfuelingsolutions.issp.data.GlobalData
import com.doverfuelingsolutions.issp.utils.DFSToastUtil
import com.doverfuelingsolutions.issp.utils.StringUtil
import com.doverfuelingsolutions.issp.utils.log.DFSLog
import com.doverfuelingsolutions.issp.view.LoginActivity
import kotlinx.coroutines.*

class LoginTokenRefresher {

    private var job: Job? = null

    fun start(activity: Activity) {
        // LoginToken is valid only for two hours and needs to be refreshed.
        job = GlobalScope.launch(Dispatchers.IO) {
            // 8 minutes left for payment process.
            val expireMoment = GlobalData.accessTokenExpire.get()
            val delayTime = expireMoment - 480_000 - System.currentTimeMillis()
            if (delayTime > 0) delay(delayTime)
            val result = SystemApi.login(GlobalData.accountName.get(), GlobalData.password.get())
            if (result.success) {
                DFSLog.d("loginToken refresh succeeded")
                // In case view remains for more than 2 hours.
                start(activity)
            } else {
                DFSLog.d("loginToken refresh failed: ${result.message}")
                GlobalData.isLogin = false
                val msg = StringUtil.get(R.string.fail_refresh_login)
                DFSToastUtil.fail(msg)
                // Back to login.
                activity.finish()
                LoginActivity.start(
                    activity,
                    bundleOf(
                        Pair(LoginActivity.autoLogin, false),
                        Pair(LoginActivity.loginMessage, msg),
                    )
                )
            }
        }
    }

    fun stop() {
        job?.let {
            if (it.isActive) it.cancel()
        }
    }
}