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

import android.content.Intent
import androidx.lifecycle.lifecycleScope
import com.base.pdfviewerscannerwhite.databinding.ActivityPdfLoadingBinding
import com.base.pdfviewerscannerwhite.helper.BaseActivity
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

class PdfLoadingActivity : BaseActivity<ActivityPdfLoadingBinding>() {

    private val TAG = "PdfLoadingActivity"
    private var srcPath: String = ""
    private var newName: String = ""
    private var splitIndex: List<Int> = listOf()
    private lateinit var pdfPresenter: PdfPresenter

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

    var isFinishBoolean: Boolean = false
    var newPdfFile: File? = null
    override fun initView() {
        pdfPresenter = PdfPresenter(this)
        initSpPa()

        pdfPresenter.splitPdf(File(srcPath), newName, splitIndex, finishAction = {
            newPdfFile = it
            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)
        }
        if (newPdfFile == null) {
            toast("split pdf failed!")
            finish()
            return@launch
        }
        startActivity(Intent(this@PdfLoadingActivity, PdfActivity::class.java).apply {
            putExtra("path", newPdfFile?.absolutePath ?: "")
        })
    }

    private fun initSpPa() {
        srcPath = intent?.extras?.getString("srcPath", "") ?: ""
        newName = intent?.extras?.getString("newName", "") ?: ""
        splitIndex = intent.extras?.getString("splitIndex")?.split(",")?.map { it.toInt() } ?: listOf()
    }


}