package com.base.pdfreaderallpdfreader.ui.main

import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import androidx.core.view.GravityCompat
import androidx.core.view.updatePadding
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.findNavController
import com.base.pdfreaderallpdfreader.R
import com.base.pdfreaderallpdfreader.ads.AdmobHelper
import com.base.pdfreaderallpdfreader.ads.AdmobHelper.lastScanShowAd
import com.base.pdfreaderallpdfreader.base.BaseActivity
import com.base.pdfreaderallpdfreader.databinding.ActivityMainBinding
import com.base.pdfreaderallpdfreader.helper.ConfigHelper
import com.base.pdfreaderallpdfreader.ui.feedback.FeedbackActivity
import com.base.pdfreaderallpdfreader.ui.language.LanguageActivity
import com.base.pdfreaderallpdfreader.ui.pdf.PdfActivity
import com.base.pdfreaderallpdfreader.ui.search.SearchActivity
import com.base.pdfreaderallpdfreader.ui.view.MainDialog.showStoragePermission
import com.base.pdfreaderallpdfreader.ui.view.NameDialog.showDocumentRenameDialog
import com.base.pdfreaderallpdfreader.ui.view.PwdDialog.showPdfPwdDialog
import com.base.pdfreaderallpdfreader.ui.view.RateDialog.showRateDialog
import com.base.pdfreaderallpdfreader.utils.BarUtils
import com.base.pdfreaderallpdfreader.utils.LogEx
import com.base.pdfreaderallpdfreader.utils.PdfBoxUtils.checkPdfEncryption
import com.base.pdfreaderallpdfreader.utils.PermissionUtils.checkStorePermission
import com.base.pdfreaderallpdfreader.utils.ShortcutUtils.addDeskShortCut
import com.base.pdfreaderallpdfreader.utils.updateMediaStore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File


class MainActivity : BaseActivity<ActivityMainBinding>() {

    private val TAG = "MainActivity"
    override val binding: ActivityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }
    private lateinit var mainViewModel: MainViewModel

    private lateinit var navController: NavController

    override fun initView() {

        mainViewModel = ViewModelProvider(this)[MainViewModel::class.java]
        mainViewModel.initScannerLauncher(this)
        mainViewModel.handleActivityGmsScanResult = { imageUri, pdfUri ->

            LogEx.logDebug(TAG, "pdfUri=$pdfUri imageUri=$imageUri")

            val file = File(pdfUri.toString().replace("file://", ""))
            if (file.exists()) {
                showDocumentRenameDialog(file.name,
                    okAction = {
                        val child = if (it.endsWith(".pdf")) it else "$it.pdf"
                        val newFile = File(getDocumentAppDir(), child)
                        mainViewModel.copyFile(file, newFile)
                        this.updateMediaStore()
                    },
                    dismissAction = {

                    })

            } else {

            }
        }

        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.WHITE)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())
        navController = findNavController(R.id.nav_host_fragment_content_main)

        val spannableString = SpannableString(this.getString(R.string.pdf_reader))
        spannableString.setSpan(ForegroundColorSpan(Color.parseColor("#E20001")), 0, 3, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
        binding.includeMain.tvTittle.text = spannableString
        binding.tvPdfReader.text = spannableString

        if (!checkStorePermission()) {
            showStoragePermission(launcher)
        }

        addDeskShortCut()
    }

    override fun onResume() {
        super.onResume()
    }

    override fun initListener() {
        super.initListener()
        binding.includeMain.ivMenu.setOnClickListener {
            binding.drawerLayout.openDrawer(GravityCompat.START)
        }
        binding.flFanhui.setOnClickListener {
            binding.drawerLayout.closeDrawer(GravityCompat.START)
        }
        binding.includeMain.includeContentMain.llHome.setOnClickListener {
            changeHomeUI()
        }
        binding.includeMain.includeContentMain.llHome.callOnClick()
        binding.includeMain.includeContentMain.llRecent.setOnClickListener {
            changeRecentUI()
        }
        binding.includeMain.includeContentMain.llBookmark.setOnClickListener {
            changeBookMarkUI()
        }
        binding.llLanguage.setOnClickListener {
            startActivity(Intent(this, LanguageActivity::class.java))
        }
        binding.includeMain.includeContentMain.ivScan.setOnClickListener {
            if (checkStorePermission()) {
                starAdGmsScan()
            } else {
                showStoragePermission(launcher)
            }
        }
        binding.includeMain.ivSearch.setOnClickListener {
            if (checkStorePermission()) {
                startActivity(Intent(this, SearchActivity::class.java))
            } else {
                showStoragePermission(launcher)
            }
        }
        binding.llFileManager.setOnClickListener {
            if (checkStorePermission()) {
                val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
                intent.addCategory(Intent.CATEGORY_OPENABLE)
                intent.setType("application/pdf")
                intent.flags = Intent.FLAG_GRANT_WRITE_URI_PERMISSION

                launcher.launch(intent) {
                    val uri = it.data?.data
                    uri?.let {
                        jumpUriPdf(uri)
                    }
                }
            } else {
                showStoragePermission(launcher)
            }
        }
        binding.llRate.setOnClickListener {
            showRateDialog(true)
        }
        binding.llPrivacy.setOnClickListener {
            val intent = Intent(
                Intent.ACTION_VIEW,
                Uri.parse(ConfigHelper.privacyPolicy)
            )
            startActivity(intent)
        }
        binding.llFeedback.setOnClickListener {
            startActivity(Intent(this, FeedbackActivity::class.java))
        }
        binding.llShare.setOnClickListener {

        }

    }

    private fun jumpUriPdf(uri: Uri) {
        lifecycleScope.launch(Dispatchers.IO) {
            val state = checkPdfEncryption(uri = uri.toString())
            launch(Dispatchers.Main) {
                if (state == 0) {
                    startActivity(Intent(this@MainActivity, PdfActivity::class.java).apply {
                        putExtra("uri", uri.toString())
                    })
                } else {
                    showPdfPwdDialog(
                        state = state,
                        uri = uri.toString(),
                        isCheckPwd = true,
                        verificationAction = { pwd ->
                            startActivity(Intent(this@MainActivity, PdfActivity::class.java).apply {
                                putExtra("uri", uri.toString())
                                putExtra("pwd", pwd)
                            })
                        })
                }
            }
        }
    }


    private fun starAdGmsScan() {

        if (AdmobHelper.isShowScanInter() && AdmobHelper.canCommonShowAd()) {
            com.base.pdfreaderallpdfreader.ads.admob.AdmobInterstitialUtils.showInterstitialAd(this) {
                if (it) {
                    lastScanShowAd = System.currentTimeMillis()
                }
                mainViewModel.starGmsScan(this)
            }
        } else {
            mainViewModel.starGmsScan(this)
        }

    }

    private fun disSelectBottomNav() {
        binding.includeMain.includeContentMain.ivHome.isSelected = false
        binding.includeMain.includeContentMain.tvHome.isSelected = false

        binding.includeMain.includeContentMain.ivRecent.isSelected = false
        binding.includeMain.includeContentMain.tvRecent.isSelected = false

        binding.includeMain.includeContentMain.ivBookmark.isSelected = false
        binding.includeMain.includeContentMain.tvBookmark.isSelected = false
    }

    private fun changeBookMarkUI() {
        disSelectBottomNav()
        binding.includeMain.includeContentMain.ivBookmark.isSelected = true
        binding.includeMain.includeContentMain.tvBookmark.isSelected = true

        navController.popBackStack()
        navController.navigate(R.id.nav_bookmarkFragment)
    }

    private fun changeRecentUI() {
        disSelectBottomNav()
        binding.includeMain.includeContentMain.ivRecent.isSelected = true
        binding.includeMain.includeContentMain.tvRecent.isSelected = true

        navController.popBackStack()
        navController.navigate(R.id.nav_recentFragment)
    }

    private fun changeHomeUI() {
        disSelectBottomNav()
        binding.includeMain.includeContentMain.ivHome.isSelected = true
        binding.includeMain.includeContentMain.tvHome.isSelected = true

        navController.popBackStack()
        navController.navigate(R.id.nav_homeFragment)
    }

}