package com.base.pdfreaderallpdfreader.ui.pdf

import android.content.Intent
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.artifex.mupdfdemo.MuPDFCore
import com.base.pdfreaderallpdfreader.ads.AdmobHelper
import com.base.pdfreaderallpdfreader.ads.admob.AdmobInterstitialUtils
import com.base.pdfreaderallpdfreader.base.BaseActivity
import com.base.pdfreaderallpdfreader.bean.ConstObject.DO_MERGE_PDF
import com.base.pdfreaderallpdfreader.bean.ConstObject.DO_SAVE_PDF
import com.base.pdfreaderallpdfreader.bean.ConstObject.DO_SPLIT_PDF
import com.base.pdfreaderallpdfreader.databinding.ActivityPdfLoadingBinding
import com.base.pdfreaderallpdfreader.utils.LogEx
import com.base.pdfreaderallpdfreader.utils.ToastUtils.toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.io.File
import kotlin.random.Random

class PdfLoadingActivity : BaseActivity<ActivityPdfLoadingBinding>() {

    private val TAG = "PdfLoadingActivity"
    private var doWhat = ""
    private var srcPath: String = ""
    private var newPath: String = ""
    private var pwd: String? = null
    private var splitIndex: List<Int> = listOf()
    private lateinit var pdfViewModel: PdfViewModel

    override val binding: ActivityPdfLoadingBinding by lazy {
        ActivityPdfLoadingBinding.inflate(layoutInflater)
    }

    private var isFinishBoolean: Boolean = false
    private var progressFinishAction: (() -> Unit)? = null

    var resultFile: File? = null

    override fun onResume() {
        super.onResume()
//        updateAppLanguage(MyApplication.pdfLoadingLanguage) {
//            MyApplication.pdfLoadingLanguage = it
//        }
    }

    private fun progressFinishAd(next: () -> Unit) {
        if (AdmobHelper.canCommonShowAd()) {
            AdmobInterstitialUtils.showInterstitialAd(this) {
                next.invoke()
            }
        } else {
            next.invoke()
        }
    }

    override fun initView() {
//        if (checkNeedRecreate(MyApplication.pdfLoadingLanguage)) {
//            return
//        }

        pdfViewModel = ViewModelProvider(this)[PdfViewModel::class.java]
        initSpPa()
        pdfViewModel.password = pwd

        when (doWhat) {
            DO_SPLIT_PDF -> {
                progressFinishAction = {
                    progressFinishAd {
                        if (resultFile != null) {
                            startActivity(Intent(this, PdfActivity::class.java).apply {
                                putExtra("path", resultFile?.absolutePath ?: "")
                            })
                        } else {
                            toast("split pdf failed")
                        }
                        finish()
                    }

                }
                pdfViewModel.splitPdf(srcPath, newPath, splitIndex, finishAction = {
                    resultFile = it
                    isFinishBoolean = true
                })
            }

            DO_SAVE_PDF -> {
                muPDFCore?.save()
                muPDFCore = null
                progressFinishAction = {
                    progressFinishAd {
                        startActivity(Intent(this, PdfActivity::class.java).apply {
                            putExtra("path", srcPath)
                        })
                        finish()
                    }
                }
                lifecycleScope.launch {
                    delay(Random.nextLong(1500, 2500))
                    isFinishBoolean = true
                }

            }

            DO_MERGE_PDF -> {
                progressFinishAction = {
                    progressFinishAd {
                        startActivity(Intent(this, PdfActivity::class.java).apply {
                            putExtra("path", newPath)
                        })
                        finish()
                    }
                }
                pdfViewModel.mergePdf(newPath) {
                    isFinishBoolean = true
                }
            }
        }

        startProgress()
    }

    private fun startProgress() = lifecycleScope.launch(Dispatchers.Main) {
        while (isActive) {
            if (isFinishBoolean) {
                binding.progressBar.progress = 100
                delay(200)
                break
            } else {
                binding.progressBar.progress += 2
            }
            delay(500)
        }
        progressFinishAction?.invoke()
    }

    private fun initSpPa() {
        doWhat = intent?.extras?.getString("doWhat", "") ?: ""
        srcPath = intent?.extras?.getString("srcPath", "") ?: ""
        pwd = intent.extras?.getString("pwd")
        newPath = intent?.extras?.getString("newPath", "") ?: ""
        splitIndex = intent.extras?.getString("splitIndex")?.split(",")?.map { it.toInt() } ?: listOf()
        LogEx.logDebug(TAG, "initSpPa doWhat=$doWhat srcPath=$srcPath pwd=$pwd newPath=$newPath splitIndex=$splitIndex")
    }

    companion object {
        var muPDFCore: MuPDFCore? = null

    }

    override fun onDestroy() {
        super.onDestroy()
        muPDFCore?.onDestroy()
    }


}