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

import android.annotation.SuppressLint
import android.content.Intent
import androidx.activity.addCallback
import com.base.pdfviewerscannerwhite.bean.PdfPageBean
import com.base.pdfviewerscannerwhite.databinding.ActivityPdfBinding
import com.base.pdfviewerscannerwhite.helper.BaseActivity
import com.base.pdfviewerscannerwhite.ui.view.DialogView.showPdfMoreDialog
import com.base.pdfviewerscannerwhite.utils.LogEx
import com.base.pdfviewerscannerwhite.utils.PermissionUtils.checkStorePermission
import com.base.pdfviewerscannerwhite.utils.PermissionUtils.requestStorePermission
import com.base.pdfviewerscannerwhite.utils.SpStringUtils
import com.base.pdfviewerscannerwhite.utils.SpStringUtils.LAST_VIEW_KEY
import com.base.pdfviewerscannerwhite.utils.ToastUtils.toast
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle
import com.tom_roush.pdfbox.pdmodel.PDDocument
import java.io.File

class PdfActivity : BaseActivity<ActivityPdfBinding>(), PdfView {

    private val TAG = "PdfActivity"

    private lateinit var pdfPresenter: PdfPresenter

    override val binding: ActivityPdfBinding by lazy {
        ActivityPdfBinding.inflate(layoutInflater)
    }
    private lateinit var adapter: PdfPagerAdapter

    var pafPath = ""
    private var pageNumber = 0

    override fun initView() {

        pdfPresenter = PdfPresenter(this, this)

        pafPath = intent.extras?.getString("path", "") ?: ""
        LogEx.logDebug(TAG, "pafPath=$pafPath")

        SpStringUtils.addSpString(LAST_VIEW_KEY, "${pafPath}_${System.currentTimeMillis()}")
        initAdapter()


        if (checkStorePermission()) {
            pdfPresenter.iniPdfPage(pafPath)
            loadPdf()
        } else {
            requestStorePermission(launcher) {
                pdfPresenter.iniPdfPage(pafPath)
                loadPdf()
            }
        }

    }

    override fun initListener() {
        super.initListener()

        onBackPressedDispatcher.addCallback {
            finishToMain()
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }

        binding.ivMore.setOnClickListener {
            showPdfMoreDialog(this, pageNumber, pafPath)
        }




    }

    private fun initAdapter() {
        adapter = PdfPagerAdapter(pafPath)
        adapter.clickAction = { pageIndex ->
            binding.pdfview.jumpTo(pageIndex, true)
        }
        binding.rvPager.adapter = adapter
    }

    private fun loadPdf() {
        try {
            val file = File(pafPath)
            if (!file.exists()) {
                toast("pdf file not exists")
            }
            PDDocument.load(file)
            loadPdfView(file)
        } catch (e: Exception) {

        }
    }


    @SuppressLint("SetTextI18n")
    private fun loadPdfView(file: File, password: String = "") {

        binding.pdfview.fromFile(file)
            .defaultPage(0)
            .enableAnnotationRendering(true)
            .scrollHandle(DefaultScrollHandle(this))
            .onPageChange { page, pageCount ->
                binding.tvPageCount.text = "${page + 1}/$pageCount"
                adapter.changeSelectPager(page)
            }
            .spacing(10)
            .onPageError { page, t ->
            }.password(password).load()

        binding.pdfview
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        pdfPresenter.handler = binding.root.handler
    }

    override fun initPdfPageRv(items: List<PdfPageBean>) {
        adapter.submitList(items)
        pageNumber = items.size
    }

    override fun jumpPage(pageIndex: Int) {
        binding.pdfview.jumpTo(pageIndex)
    }

    override fun jumpSplit() {
        startActivity(Intent(this, PdfSplitActivity::class.java).apply {
            putExtra("path", pafPath)
        })
    }


}