package com.base.pdfviewerscannerwhite.ui.main

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.base.pdfviewerscannerwhite.R
import com.base.pdfviewerscannerwhite.ads.admob.AdmobBannerUtils
import com.base.pdfviewerscannerwhite.bean.ConstObject
import com.base.pdfviewerscannerwhite.bean.ConstObject.BOOKMARK_DATA_TYPE
import com.base.pdfviewerscannerwhite.bean.ConstObject.DOCUMENT_DATA_TYPE
import com.base.pdfviewerscannerwhite.bean.ConstObject.NOTIFICATION_ACTION_BOOKMARK
import com.base.pdfviewerscannerwhite.bean.ConstObject.NOTIFICATION_ACTION_DOCUMENT
import com.base.pdfviewerscannerwhite.bean.ConstObject.NOTIFICATION_ACTION_NEW_IMAGE_PDF
import com.base.pdfviewerscannerwhite.bean.ConstObject.RECENT_DATA_TYPE
import com.base.pdfviewerscannerwhite.bean.ConstObject.SHORTCUT_MERGE_PDF
import com.base.pdfviewerscannerwhite.bean.ConstObject.SHORTCUT_SCAN_PDF
import com.base.pdfviewerscannerwhite.bean.ConstObject.SHORTCUT_SPLIT_PDF
import com.base.pdfviewerscannerwhite.bean.ConstObject.mainStartTimes
import com.base.pdfviewerscannerwhite.bean.ConstObject.todayShowNotificationDialog
import com.base.pdfviewerscannerwhite.bean.DocumentBean
import com.base.pdfviewerscannerwhite.databinding.ActivityMain2Binding
import com.base.pdfviewerscannerwhite.helper.BaseActivity
import com.base.pdfviewerscannerwhite.helper.MyApplication
import com.base.pdfviewerscannerwhite.ui.document.excel.ExcelActivity
import com.base.pdfviewerscannerwhite.ui.document.pdf.PdfActivity
import com.base.pdfviewerscannerwhite.ui.document.pdf.PdfSelectActivity
import com.base.pdfviewerscannerwhite.ui.document.ppt.PptActivity
import com.base.pdfviewerscannerwhite.ui.document.word.WordActivity
import com.base.pdfviewerscannerwhite.ui.view.DialogView.showAppExitDialog
import com.base.pdfviewerscannerwhite.ui.view.DialogView.showDefaultBottomDialog
import com.base.pdfviewerscannerwhite.ui.view.DialogView.showDeleteDialog
import com.base.pdfviewerscannerwhite.ui.view.DialogView.showDocumentRenameDialog
import com.base.pdfviewerscannerwhite.ui.view.DialogView.showNotificationDialog
import com.base.pdfviewerscannerwhite.ui.view.DialogView.showStoragePermission
import com.base.pdfviewerscannerwhite.ui.view.PdfDialog.showPdfPwdDialog
import com.base.pdfviewerscannerwhite.ui.view.RateDialog.showRateDialog
import com.base.pdfviewerscannerwhite.utils.AppPreferences
import com.base.pdfviewerscannerwhite.utils.IntentShareUtils.shareMutDocuments
import com.base.pdfviewerscannerwhite.utils.LogEx
import com.base.pdfviewerscannerwhite.utils.PermissionUtils.checkNotificationPermission
import com.base.pdfviewerscannerwhite.utils.PermissionUtils.checkStorePermission
import com.base.pdfviewerscannerwhite.utils.ShortcutUtils.addDeskShortCut
import com.base.pdfviewerscannerwhite.utils.UmpUtils
import com.base.pdfviewerscannerwhite.utils.updateMediaStore
import java.io.File

class MainActivity : BaseActivity<ActivityMain2Binding>(), MainView {

    private val TAG = "MainActivity"
    lateinit var mainPresenter: MainPresenter
    override val binding: ActivityMain2Binding by lazy {
        ActivityMain2Binding.inflate(layoutInflater)
    }
    private val documentFragment: DocumentFragment by lazy {
        DocumentFragment(DOCUMENT_DATA_TYPE)
    }
    private val recentFragment: DocumentFragment by lazy {
        DocumentFragment(RECENT_DATA_TYPE)
    }
    private val bookmarkFragment: DocumentFragment by lazy {
        DocumentFragment(BOOKMARK_DATA_TYPE)
    }
    private val toolFragment: ToolFragment by lazy {
        ToolFragment()
    }
    private var actionId: String = ""
    private var currentFragment: Fragment = documentFragment


    override fun initView() {

        mainPresenter = MainPresenter(this, this, lifecycleScope)
        mainPresenter.initScannerLauncher(this)

        actionId = intent.extras?.getString("actionId") ?: ""
        LogEx.logDebug(TAG, "initView actionId=$actionId", true)


        addDeskShortCut()

        if (checkStorePermission() && mainStartTimes >= 2) {
            if (!ConstObject.setDefault && !todayShowNotificationDialog) {
                showDefaultBottomDialog()
            } else if (!checkNotificationPermission() && !todayShowNotificationDialog) {
                showNotificationDialog(launcher)
            }
        }

    }


    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        actionId = intent?.extras?.getString("actionId") ?: ""
        LogEx.logDebug(TAG, "onNewIntent actionId=$actionId", true)
        actionIdOperation()
    }

    private fun actionIdOperation() {
        if (actionId == SHORTCUT_SCAN_PDF) {
            useGmsScanFunction()
        }
        if (actionId == SHORTCUT_SPLIT_PDF) {
            startActivity(Intent(this, PdfSelectActivity::class.java).apply {
                putExtra("doWhat", ConstObject.DO_SPLIT_PDF)
            })
            return
        }
        if (actionId == SHORTCUT_MERGE_PDF) {
            startActivity(Intent(this, PdfSelectActivity::class.java).apply {
                putExtra("doWhat", ConstObject.DO_MERGE_PDF)
            })
            return
        }
        if (actionId == NOTIFICATION_ACTION_DOCUMENT) {
            binding.llDocument.callOnClick()
            return
        }
        if (actionId == NOTIFICATION_ACTION_BOOKMARK) {
            binding.llBookmark.callOnClick()
            return
        }
        if (actionId == NOTIFICATION_ACTION_NEW_IMAGE_PDF) {
            useGmsScanFunction()
        }
    }

    private fun closeScanGuide() {
        binding.flScanGuide.visibility = View.GONE
        dialogRequestStep()
    }

    override fun handleActivityGmsScanResult(imageUri: Uri?, pdfUri: Uri?) {
//        LogEx.logDebug(TAG, "imageUri=$imageUri")
        LogEx.logDebug(TAG, "pdfUri=$pdfUri")
        val file = File(pdfUri.toString().replace("file://", ""))
        if (file.exists()) {
//            binding.tvTest.text = "imageUri=$imageUri\n\n\n\npdfUri=$pdfUri"
            showDocumentRenameDialog(file.name,
                okAction = {
                    val newFile = File(mainPresenter.getDocumentAppDir(), "$it.pdf")
                    mainPresenter.copyFile(file, newFile)
                    this.updateMediaStore()
                },
                dismissAction = {
                    avoidScanThenDialog = false
                    dialogRequestStep()
                })
        } else {
            avoidScanThenDialog = false
            dialogRequestStep()
        }

    }

    var isPause = false
    override fun onPause() {
        super.onPause()
        isPause = true
    }

    override fun onResume() {
        super.onResume()

        val isRecreate = updateAppLanguage(MyApplication.mainLanguage, TAG) {
            supportFragmentManager.beginTransaction().apply {
                remove(documentFragment)
                remove(recentFragment)
                remove(bookmarkFragment)
                remove(toolFragment)
                commit()
            }
            MyApplication.mainLanguage = it
        }

        LogEx.logDebug(TAG, "isRecreate=$isRecreate mainStartTimes=$mainStartTimes")
        if (!isRecreate) {
            mainStartTimes++
        } else {
            return
        }

//        val restUmpCount = AppPreferences.getInstance().getString("restUmpCount", "50").toInt()
//        //ump请求重置
//        if (mainStartTimes % restUmpCount == 0) {
//            UmpUtils.umpCalled = false
//        }

        mainPresenter.initAllDocumentData()

        //scan guide
        if (mainStartTimes == 1) {
            binding.flScanGuide.visibility = View.VISIBLE
            return
        }

        //避免scan回调的任意弹窗
        if (!avoidScanThenDialog) {
            dialogRequestStep()
        }

        val canShowRateN = AppPreferences.getInstance().getString("canShowRateN", "4").toInt()
        if (isPause && mainStartTimes >= canShowRateN) {
            showRateDialog()
        }
    }

    //弹窗请求顺序
    private fun dialogRequestStep() {
        LogEx.logDebug(TAG, "dialogRequestStep 1")
        if (!checkStorePermission()) {
            LogEx.logDebug(TAG, "dialogRequestStep 2")
            showPermissionDialog()
        } else {
            if (!bannerShowed) {
                LogEx.logDebug(TAG, "dialogRequestStep 3")
                showMainBanner()
                return
            }
            //通知弹窗
//            if (!todayShowNotificationDialog && !checkNotificationPermission()) {
//                todayShowNotificationDialog = true
//                showNotificationDialog(launcher)
//            } else {
//                if (!ConstObject.setDefault) {
//                    showDefaultBottomDialog()
//                } else {
//                    showRateDialog()
//                }
//            }
        }
    }

    private var permissionDialog: Dialog? = null
    private fun showPermissionDialog() {
        if (permissionDialog == null) {
            permissionDialog = showStoragePermission(launcher,
                noLauncherAction = {
                    showMainBanner()
                },
                dismissAction = {
                    permissionDialog = null
                })
        }
    }

    private fun showMainBanner() {
        if (!bannerShowed) {
            bannerShowed = true
            AdmobBannerUtils.showCollapsibleBannerAd(this, binding.flBanner) {
                //通知弹窗
//                if (!todayShowNotificationDialog && !checkNotificationPermission()) {
//                    todayShowNotificationDialog = true
//                    showNotificationDialog(launcher)
//                } else {
//                    if (!ConstObject.setDefault) {
//                        showDefaultBottomDialog()
//                    } else {
//                        showRateDialog()
//                    }
//                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        LogEx.logDebug(TAG, "onDestroy")
        mainPresenter.scannerLauncher = null
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        LogEx.logDebug(TAG, "onSaveInstanceState")
    }

    var isDocumentAdd: Boolean = false
    var isRecentAdd: Boolean = false
    var isBookmarkAdd: Boolean = false
    var isToolAdd: Boolean = false

    @SuppressLint("MissingSuperCall")
    override fun onBackPressed() {
        LogEx.logDebug(TAG, "onBackPressed")
        showAppExitDialog()
    }

    //OnBackPressedCallback 并将 isEnabled 设置为 false 时，默认的返回键行为将被禁用。
    lateinit var callback: OnBackPressedCallback
    override fun initListener() {
        super.initListener()

        callback = object : OnBackPressedCallback(false) {
            override fun handleOnBackPressed() {
                LogEx.logDebug(TAG, "handleOnBackPressed")
                if (currentFragment is DocumentFragment) {
                    val documentFragment = (currentFragment as DocumentFragment)
                    LogEx.logDebug(TAG, "handleOnBackPressed uiMode=${documentFragment.uiMode}")
                    if (documentFragment.uiMode == ConstObject.UI_MODE_SELECT) {
                        documentFragment.changeSelectUI(false)
                    }
                    if (documentFragment.uiMode == ConstObject.UI_MODE_SEARCH) {
                        documentFragment.changeSearchUI(false)
                    }
                }
            }
        }
        onBackPressedDispatcher.addCallback(callback)

        binding.llDocument.setOnClickListener {
            changeTabSelect(it)

            supportFragmentManager.beginTransaction().apply {

                if (!isDocumentAdd) {
                    add(R.id.fl_container, documentFragment)
                }

                hide(bookmarkFragment)
                hide(toolFragment)
                hide(recentFragment)
                show(documentFragment)
                commit()
            }
            currentFragment = documentFragment
            isDocumentAdd = true
            binding.ivScan.visibility = View.VISIBLE
        }
        binding.llDocument.callOnClick()
        binding.llRecent.setOnClickListener {
            changeTabSelect(it)
            supportFragmentManager.beginTransaction().apply {
                if (!isRecentAdd) {
                    add(R.id.fl_container, recentFragment)
                }
                hide(documentFragment)
                hide(bookmarkFragment)
                hide(toolFragment)
                show(recentFragment)
                commit()
            }
            currentFragment = recentFragment
            isRecentAdd = true
            binding.ivScan.visibility = View.VISIBLE
        }
        binding.llBookmark.setOnClickListener {
            changeTabSelect(it)
            supportFragmentManager.beginTransaction().apply {
                if (!isBookmarkAdd) {
                    add(R.id.fl_container, bookmarkFragment)
                }

                hide(documentFragment)
                hide(recentFragment)
                hide(toolFragment)
                show(bookmarkFragment)
                commit()
            }
            currentFragment = bookmarkFragment
            isBookmarkAdd = true
            binding.ivScan.visibility = View.VISIBLE
        }
        binding.llTool.setOnClickListener {
            changeTabSelect(it)
            supportFragmentManager.beginTransaction().apply {
                if (!isToolAdd) {
                    add(R.id.fl_container, toolFragment)
                }
                hide(documentFragment)
                hide(recentFragment)
                hide(bookmarkFragment)
                show(toolFragment)
                commit()
            }
            currentFragment.userVisibleHint = true
            currentFragment = toolFragment
            isToolAdd = true
            binding.ivScan.visibility = View.INVISIBLE
        }
        binding.llDelete.setOnClickListener {
            if (currentFragment is DocumentPageFragment) {
                val fragment = (currentFragment as DocumentPageFragment)
                showDeleteDialog {
                    val list = fragment.getSelectItems()
                    mainPresenter.deleteList(list)
                    fragment.removeList(list)
                }
            }
        }
        binding.llShare.setOnClickListener {
            shareDocument()
        }
        binding.ivScan.setOnClickListener {
            useGmsScanFunction()
        }
        binding.flScanGuide.setOnClickListener {
            closeScanGuide()
        }
        binding.tvTryScan.setOnClickListener {
            useGmsScanFunction()
        }
        binding.ivScanGuide.setOnClickListener {
            useGmsScanFunction()
        }
        actionIdOperation()
    }

    fun useGmsScanFunction() {
        avoidScanThenDialog = true
        binding.flScanGuide.visibility = View.GONE
        mainPresenter.starAdGmsScan(this)
    }


    private fun shareDocument() {
        if (currentFragment is DocumentPageFragment) {
            val documentFragment = (currentFragment as DocumentPageFragment)
            val items = documentFragment.getSelectItems()
            if (items.isNotEmpty()) {
                shareMutDocuments(documentFragment.type, items.map { it.uri } as ArrayList<Uri>)
            }

        }
    }

    private fun changeTabSelect(selectView: View) {
        binding.llDocument.isSelected = selectView == binding.llDocument
        binding.llRecent.isSelected = selectView == binding.llRecent
        binding.llBookmark.isSelected = selectView == binding.llBookmark
        binding.llTool.isSelected = selectView == binding.llTool

    }

    fun changeSelectUI(show: Boolean) {
        if (show) {
            binding.ivScan.visibility = View.INVISIBLE
            binding.llDocument.visibility = View.INVISIBLE
            binding.llRecent.visibility = View.INVISIBLE
            binding.llBookmark.visibility = View.INVISIBLE
            binding.llTool.visibility = View.INVISIBLE

            binding.llDelete.visibility = View.VISIBLE
            binding.llShare.visibility = View.VISIBLE
        } else {
            binding.llDelete.visibility = View.INVISIBLE
            binding.llShare.visibility = View.INVISIBLE

            binding.ivScan.visibility = View.VISIBLE
            binding.llDocument.visibility = View.VISIBLE
            binding.llRecent.visibility = View.VISIBLE
            binding.llBookmark.visibility = View.VISIBLE
            binding.llTool.visibility = View.VISIBLE
        }

    }


    override fun refreshPageList() {
        if (currentFragment is DocumentFragment) {
            (currentFragment as DocumentFragment).currentPage.refreshData()
        }
    }


    fun changeSearchUI(show: Boolean) {
        if (show) {
            binding.ivScan.visibility = View.INVISIBLE
            binding.llBottom.visibility = View.GONE
        } else {
            binding.ivScan.visibility = View.VISIBLE
            binding.llBottom.visibility = View.VISIBLE
        }

    }

    companion object {

        var bannerShowed: Boolean = false//banner已经显示
        var avoidScanThenDialog: Boolean = false//扫描回调后避免任何弹窗

        fun Activity.jumpDocument(item: DocumentBean) {
            if (item.type == DocumentBean.TYPE_PDF) {
                if (item.state == 0) {
                    startActivity(Intent(this, PdfActivity::class.java).apply {
                        putExtra("path", item.path)
                    })
                }
                if (item.state == 1) {
                    showPdfPwdDialog(
                        state = item.state,
                        path = item.path,
                        isCheckPwd = true,
                        verificationAction = { pwd ->
                            startActivity(Intent(this, PdfActivity::class.java).apply {
                                putExtra("path", item.path)
                                putExtra("pwd", pwd)
                            })
                        })
                }
            }
            if (item.type == DocumentBean.TYPE_WORD) {
                WordActivity.wordDocumentBean = item
                WordActivity.launchDocViewer(this, 3, item.path, -1, 100)
            }
            if (item.type == DocumentBean.TYPE_EXCEL) {
                ExcelActivity.excelDocumentBean = item
                ExcelActivity.launchDocViewer(this, 3, item.path, -1, 100)
            }
            if (item.type == DocumentBean.TYPE_PPT) {
                PptActivity.pptDocumentBean = item
                PptActivity.launchDocViewer(this, 3, item.path, -1, 100)
            }
        }
    }


}