package com.base.pdfreaderallpdfreader.ui.view

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.core.content.FileProvider
import androidx.core.widget.addTextChangedListener
import com.base.pdfreaderallpdfreader.R
import com.base.pdfreaderallpdfreader.bean.DocumentBean
import com.base.pdfreaderallpdfreader.databinding.DialogPageNumberBinding
import com.base.pdfreaderallpdfreader.databinding.DialogPdfHomeMoreBinding
import com.base.pdfreaderallpdfreader.databinding.DialogPdfMoreBinding
import com.base.pdfreaderallpdfreader.ui.main.saveBookmarkChange
import com.base.pdfreaderallpdfreader.ui.pdf.PdfActivity
import com.base.pdfreaderallpdfreader.ui.pdf.PdfActivity.Companion.jumpMerge
import com.base.pdfreaderallpdfreader.ui.pdf.PdfActivity.Companion.jumpSplit
import com.base.pdfreaderallpdfreader.ui.view.DialogView.showDeleteDialog
import com.base.pdfreaderallpdfreader.ui.view.DocumentDialog.showDocumentDetail
import com.base.pdfreaderallpdfreader.ui.view.NameDialog.showDocumentRenameDialog
import com.base.pdfreaderallpdfreader.ui.view.PwdDialog.showPdfPwdDialog
import com.base.pdfreaderallpdfreader.utils.IntentShareUtils
import com.base.pdfreaderallpdfreader.utils.KotlinExt.toFormatSize
import com.base.pdfreaderallpdfreader.utils.KotlinExt.toFormatTime
import com.base.pdfreaderallpdfreader.utils.LogEx
import com.base.pdfreaderallpdfreader.utils.NumberRangeFilter
import com.base.pdfreaderallpdfreader.utils.PermissionUtils.checkStorePermission
import com.base.pdfreaderallpdfreader.utils.SpStringUtils
import com.base.pdfreaderallpdfreader.utils.SpStringUtils.BOOKMARK_KEY
import com.base.pdfreaderallpdfreader.utils.ToastUtils.toast
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import java.io.File


object PdfDialog {

    //pdf首页弹窗
    @SuppressLint("NotifyDataSetChanged")
    fun Activity.showPdfHomeMoreDialog(
        item: DocumentBean,
        dialogCallBack: DialogCallBack
    ): BottomSheetDialog {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val binding = DialogPdfHomeMoreBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(true)

        dialog.show()

        val parentView = binding.root.parent as View
        val behavior = BottomSheetBehavior.from(parentView)
        //展开
        behavior.state = BottomSheetBehavior.STATE_EXPANDED

        val file = File(item.path)
        binding.tvName.text = file.name
        binding.tvInfo.text = file.lastModified().toFormatTime() + " " + file.length().toFormatSize()
        if (item.isBookmarked) {
            binding.ivBookmark.setImageResource(R.mipmap.pdf_bookmark_s)
        } else {
            binding.ivBookmark.setImageResource(R.mipmap.pdf_bookmark_n)
        }
        binding.ivBookmark.setOnClickListener {
            item.isBookmarked = !item.isBookmarked
            if (item.isBookmarked) {
                binding.ivBookmark.setImageResource(R.mipmap.pdf_bookmark_s)
            } else {
                binding.ivBookmark.setImageResource(R.mipmap.pdf_bookmark_n)
            }
            dialogCallBack.changeBookmark(item.path, item.isBookmarked)
        }
        binding.llRename.setOnClickListener {
            showDocumentRenameDialog(file.name, okAction = { newName ->
                dialog.dismiss()
                dialogCallBack.renameDocumentBean(file, newName)
            })
        }
        binding.llSplit.setOnClickListener {
            dialog.dismiss()
            if (item.state == 1) {
                showPdfPwdDialog(
                    state = item.state, path = item.path, firstDialog = dialog, isCheckPwd = true, verificationAction = {
                        PdfActivity.jumpSplit(this, item.path)
                    })
            } else {
                PdfActivity.jumpSplit(this, item.path)
            }
        }
        binding.llMerge.setOnClickListener {
            dialog.dismiss()
            PdfActivity.jumpMerge(this)
        }
        binding.llDelete.setOnClickListener {
            dialog.dismiss()
            showDeleteDialog {
                dialogCallBack.deleteDocument(item)
            }
        }
        binding.llDetail.setOnClickListener {
            showDocumentDetail(item.path)
        }
        binding.llShare.setOnClickListener {
            runCatching {
                item.uri?.let {
                    val intent = IntentShareUtils.sharePdfIntent(it)
                    startActivity(intent)
                }
            }
        }
        if (item.state == 1) {
            binding.ivPdf.setImageResource(R.mipmap.rv_pdf_lock)
            binding.tvLock.text = getString(R.string.unlock_pdf)
        }
        if (item.state == 0) {
            binding.ivPdf.setImageResource(R.mipmap.r_pdf)
            binding.tvLock.text = getString(R.string.lock_pdf)
        }
        binding.llLock.setOnClickListener {
            showPdfPwdDialog(state = item.state, path = item.path,
                firstDialog = dialog,
                isCheckPwd = false,
                encryptionAction = {
                    dialog.dismiss()
                    dialogCallBack.changePdfLock(item)
                }
            )
        }
        dialog.setOnDismissListener {
        }
        return dialog
    }

    fun Activity.showPdfMoreDialog(
        pdfActivity: PdfActivity,
        pageNumber: Int,
        pafPath: String,
        uri: String? = null,
        pwd: String? = null,
    ) {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val binding = DialogPdfMoreBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(true)

        dialog.show()

        val parentView = binding.root.parent as View
        val behavior = BottomSheetBehavior.from(parentView)
        //展开
        behavior.state = BottomSheetBehavior.STATE_EXPANDED

        binding.llJump.setOnClickListener {
            showJumpPageNumberDialog(pageNumber) { pageIndex ->
                dialog.dismiss()
                pdfActivity.jumpPage(pageIndex)
            }
        }
        binding.llMerge.setOnClickListener {
            dialog.dismiss()
            jumpMerge(pdfActivity)

        }
        binding.llSplit.setOnClickListener {
            dialog.dismiss()
            jumpSplit(pdfActivity, pafPath, uri, pwd)
        }
        binding.llDetail.setOnClickListener {
            showDocumentDetail(pafPath)
        }
        val bookmarkList = SpStringUtils.getSpStringList(BOOKMARK_KEY)
        var isBookmarked = bookmarkList.contains(pafPath)
        if (isBookmarked) {
            binding.ivBookmark.setImageResource(R.mipmap.pdf_bookmark_s)
        } else {
            binding.ivBookmark.setImageResource(R.mipmap.pdf_bookmark_n)
        }
        binding.ivBookmark.setOnClickListener {
            isBookmarked = !isBookmarked
            if (isBookmarked) {
                binding.ivBookmark.setImageResource(R.mipmap.pdf_bookmark_s)
            } else {
                binding.ivBookmark.setImageResource(R.mipmap.pdf_bookmark_n)
            }
            saveBookmarkChange(isBookmarked, pafPath)
        }
        binding.llShare.setOnClickListener {
            dialog.dismiss()
            runCatching {
                val pkg = this.packageName
                LogEx.logDebug("showPdfMoreDialog", "pkg=$pkg")
                val uri = FileProvider.getUriForFile(
                    this, this.packageName + ".provider", File(pafPath)
                )
                startActivity(Intent.createChooser(IntentShareUtils.sharePdfIntent(uri), "Share PDF"))
            }
        }

    }

    fun Context.showJumpPageNumberDialog(pageNumber: Int, okAction: ((pageIndex: Int) -> Unit)?) {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val binding = DialogPageNumberBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(true)

        val window = dialog.window
        window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)

        dialog.show()

        val parentView = binding.root.parent as View
        val behavior = BottomSheetBehavior.from(parentView)
        //展开
        behavior.state = BottomSheetBehavior.STATE_EXPANDED

        binding.edit.filters = arrayOf(NumberRangeFilter(1, pageNumber + 1))
        binding.edit.hint = "1 - ${pageNumber + 1}"
        binding.edit.addTextChangedListener {
            binding.tvOk.isEnabled = !it.isNullOrEmpty()
        }
        binding.edit.requestFocus()
        binding.tvOk.setOnClickListener {
            val number = binding.edit.text.toString()
            if (number.isEmpty()) {
                toast("number can't be empty!")
                return@setOnClickListener
            }
            dialog.dismiss()
            okAction?.invoke(number.toInt() - 1)
        }
    }
}