package com.cheng.blzb.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.window.OnBackInvokedDispatcher
import androidx.activity.addCallback
import androidx.core.os.BuildCompat
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import com.cheng.blzb.R
import com.cheng.blzb.common.EventConstants
import com.cheng.blzb.manager.EventReportManager
import com.cheng.blzb.ui.fragment.login.LoginFragment
import com.cheng.blzb.ui.fragment.login.onekey.OneKeyLoginFragment
import com.example.base.common.ActivityManager
import com.example.base.extensions.toast
import com.example.base.ui.BaseActivity
import com.g.gysdk.GYManager

class LoginActivity : BaseActivity() {

    private var lastBackClickTime = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val from = intent.getIntExtra("from", 0)
        if (from == 0) backApp()
    }

    override fun getFragment(): Fragment {
        val fragment = if (GYManager.getInstance().isPreLoginResultValid) {
            OneKeyLoginFragment()
        } else {
            LoginFragment()
        }
        fragment.arguments = intent.extras
        return fragment
    }

    companion object {
        fun start(activity: Activity?, vararg args: Pair<String, *>) {
            val intent = Intent(activity, LoginActivity::class.java)
            intent.putExtras(bundleOf(*args))
            activity?.startActivity(intent)
        }
    }

    @SuppressLint("UnsafeOptInUsageError")
    private fun backApp() {
        if (BuildCompat.isAtLeastT()) {
            onBackInvokedDispatcher.registerOnBackInvokedCallback(OnBackInvokedDispatcher.PRIORITY_DEFAULT) {
                exitApp()
            }
        } else {
            onBackPressedDispatcher.addCallback(this) {
                exitApp()
            }
        }
    }

    private fun exitApp() {
        if (System.currentTimeMillis() - lastBackClickTime > 1500) {
            toast(getString(R.string.exit_app))
            lastBackClickTime = System.currentTimeMillis()
        } else {
            EventReportManager.eventReport(EventConstants.EXIT_APP, "login", "")
            ActivityManager.exitApp()
        }
    }
}