package com.base.pdfviewerscannerwhite.ui.document.pdf

import android.content.Intent
import androidx.lifecycle.lifecycleScope
import com.artifex.mupdfdemo.MuPDFCore
import com.base.pdfviewerscannerwhite.ads.AdmobHelper
import com.base.pdfviewerscannerwhite.ads.admob.AdmobInterstitialUtils
import com.base.pdfviewerscannerwhite.bean.ConstObject.DO_MERGE_PDF
import com.base.pdfviewerscannerwhite.bean.ConstObject.DO_SAVE_PDF
import com.base.pdfviewerscannerwhite.bean.ConstObject.DO_SPLIT_PDF
import com.base.pdfviewerscannerwhite.databinding.ActivityPdfLoadingBinding
import com.base.pdfviewerscannerwhite.helper.BaseActivity
import com.base.pdfviewerscannerwhite.helper.MyApplication
import com.base.pdfviewerscannerwhite.utils.LogEx
import com.base.pdfviewerscannerwhite.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 pdfPresenter: PdfPresenter

    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
        }
    }

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

    }

    override fun initView() {
        pdfPresenter = PdfPresenter(this)
        initSpPa()
        pdfPresenter.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()
                    }

                }
                pdfPresenter.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()
                    }
                }
                pdfPresenter.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

    }


}