package com.cheng.blzb.ui.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.window.OnBackInvokedDispatcher
import androidx.activity.addCallback
import androidx.core.os.BuildCompat
import com.cheng.blzb.R
import com.cheng.blzb.common.EventConstants
import com.cheng.blzb.event.LogoutSuccessEvent
import com.cheng.blzb.event.PushMessageEvent
import com.cheng.blzb.manager.EventReportManager
import com.cheng.blzb.ui.fragment.main.MainFragment
import com.example.base.common.ActivityManager
import com.example.base.common.RxBus
import com.example.base.extensions.toast
import com.example.base.ui.BaseActivity
import com.example.base.utils.ClipboardUtils

class MainActivity : BaseActivity() {

    private var lastBackClickTime = 0L

    override fun getFragment() = MainFragment()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        backApp()

        RxBus.defaultInstance.toObservable(LogoutSuccessEvent::class.java).subscribe { finish() }

        handleIntent(intent)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        handleIntent(intent)
    }

    private fun handleIntent(intent: Intent?) {
        val payload = intent?.getStringExtra("payload")
        if (!TextUtils.isEmpty(payload)) {
            RxBus.defaultInstance.post(PushMessageEvent(payload!!, 3))
        } else {
            if (intent?.action == Intent.ACTION_SEND && intent.type == "text/plain") {
                val text = intent.getStringExtra(Intent.EXTRA_TEXT)
                ClipboardUtils.copyText(text)
                toast("复制成功")
                return
            }
        }
    }

    @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, "main", "")
            ActivityManager.exitApp()
        }
    }
}