package com.base.pdfviewerscannerwhite.ui.view

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.text.InputType.TYPE_CLASS_TEXT
import android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD
import android.text.InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
import android.text.method.PasswordTransformationMethod
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.pdfviewerscannerwhite.R
import com.base.pdfviewerscannerwhite.bean.DocumentBean
import com.base.pdfviewerscannerwhite.databinding.DialogPdfHomeMoreBinding
import com.base.pdfviewerscannerwhite.databinding.DialogPdfMoreBinding
import com.base.pdfviewerscannerwhite.databinding.DialogPdfPasswordBinding
import com.base.pdfviewerscannerwhite.ui.document.pdf.PdfBoxUtils
import com.base.pdfviewerscannerwhite.ui.document.pdf.PdfView
import com.base.pdfviewerscannerwhite.ui.main.DocumentFragment
import com.base.pdfviewerscannerwhite.ui.main.DocumentPageFragment
import com.base.pdfviewerscannerwhite.ui.main.MainActivity
import com.base.pdfviewerscannerwhite.ui.view.DialogView.showDeleteDialog
import com.base.pdfviewerscannerwhite.ui.view.DialogView.showDocumentDetail
import com.base.pdfviewerscannerwhite.ui.view.DialogView.showDocumentRenameDialog
import com.base.pdfviewerscannerwhite.ui.view.DialogView.showJumpPageNumberDialog
import com.base.pdfviewerscannerwhite.utils.IntentShareUtils
import com.base.pdfviewerscannerwhite.utils.KotlinExt.toFormatSize
import com.base.pdfviewerscannerwhite.utils.KotlinExt.toFormatTime
import com.base.pdfviewerscannerwhite.utils.LogEx
import com.base.pdfviewerscannerwhite.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 Context.showPdfHomeMoreDialog(
        item: DocumentBean,
        mainActivity: MainActivity,
        documentFragment: DocumentFragment,
        documentPageFragment: DocumentPageFragment,
    ): BottomSheetDialog {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val binding = DialogPdfHomeMoreBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(false)

        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.h_soucang_s)
        } else {
            binding.ivBookmark.setImageResource(R.mipmap.h_soucang_n)
        }
        binding.ivBookmark.setOnClickListener {
            item.isBookmarked = !item.isBookmarked
            if (item.isBookmarked) {
                binding.ivBookmark.setImageResource(R.mipmap.h_soucang_s)
            } else {
                binding.ivBookmark.setImageResource(R.mipmap.h_soucang_n)
            }
            mainActivity.mainPresenter.changeBookmark(item.path, item.isBookmarked, documentPageFragment)

        }
        binding.llRename.setOnClickListener {
            showDocumentRenameDialog(file.name, okAction = { newName ->
                dialog.dismiss()
                mainActivity.mainPresenter.renameDocumentBean(file, newName, documentPageFragment)
            })
        }
        binding.llSplit.setOnClickListener {
            dialog.dismiss()
            if (item.state == 1) {
                showPdfPwdDialog(
                    state = item.state, path = item.path, firstDialog = dialog, isCheckPwd = true, verificationAction = {
                        documentPageFragment.splitPdf(item.path, it)
                    })
            } else {
                documentPageFragment.splitPdf(item.path)
            }
        }
        binding.llMerge.setOnClickListener {
            dialog.dismiss()
            documentPageFragment.mergePdf(item.path)
        }
        binding.llDelete.setOnClickListener {
            dialog.dismiss()
            showDeleteDialog {
                mainActivity.mainPresenter.deleteDocument(item.path, documentPageFragment)
                documentFragment.searchDeleteDocument(item)
            }
        }
        binding.llDetail.setOnClickListener {
            showDocumentDetail(item.path)
        }
        binding.llShare.setOnClickListener {
            val intent = IntentShareUtils.sharePdfIntent(item.uri)
            runCatching {
                startActivity(intent)
            }
        }
        if (item.state == 1) {
            binding.tvLock.text = getString(R.string.unlock_pdf)
        }
        if (item.state == 0) {
            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()
                    mainActivity.mainPresenter.changePdfLock(item, documentPageFragment)
                })
        }
        dialog.setOnDismissListener {
        }
        return dialog
    }

    fun Activity.showPdfMoreDialog(
        pdfView: PdfView,
        pageNumber: Int,
        pafPath: String,
    ) {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val binding = DialogPdfMoreBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(false)

        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()
                pdfView.jumpPage(pageIndex)
            }
        }
        binding.llSplit.setOnClickListener {
            dialog.dismiss()
            pdfView.jumpSplit()
        }
        binding.llDetail.setOnClickListener {
            showDocumentDetail(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"))
            }
        }
        binding.llPrint.setOnClickListener {
            val uri = FileProvider.getUriForFile(
                this, this.packageName + ".provider", File(pafPath)
            )
            startActivity(Intent.createChooser(IntentShareUtils.sharePdfPrintIntent(uri), "Print PDF"))
        }

    }

    @SuppressLint("SetTextI18n")
    fun Context.showPdfPwdDialog(
        state: Int,
        path: String = "",
        uri: String? = null,
        firstDialog: Dialog? = null,
        isCheckPwd: Boolean = false,
        verificationAction: ((pwd: String) -> Unit)? = null,
        encryptionAction: (() -> Unit)? = null,
        cancelAction: (() -> Unit)? = null,
    ) {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val binding = DialogPdfPasswordBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(false)

        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

        if (!isCheckPwd) {
            if (state == 1) {
                binding.tvTittle.text = getString(R.string.delete_password)
                binding.tvTip.text = getString(R.string.delete_password_the_file_is_not_password_protected)
            }
            if (state == 0) {
                binding.tvTittle.text = getString(R.string.set_password)
                binding.tvTip.text = getString(R.string.set_password_protection_pdf)

            }
        } else {
            binding.tvTittle.text = getString(R.string.input_password)
            val file = File(path)
            binding.tvTip.text = getString(R.string.password_protected, file.name)
            binding.tvInputTip.visibility = View.VISIBLE
        }

        binding.edit.requestFocus()
        binding.edit.addTextChangedListener {
            binding.tvConfirm.isEnabled = it.toString().isNotEmpty()
            binding.tvErrorTip.visibility = View.GONE
        }

        binding.tvCancel.setOnClickListener {
            dialog.dismiss()
            cancelAction?.invoke()
        }
        binding.tvConfirm.setOnClickListener {

            val pwd = binding.edit.text.toString()

            if (!isCheckPwd) {

                //加锁逻辑
                if (state == 0) {
                    PdfBoxUtils.setPassword(path, pwd, pwd)
                    toast("Success Encryption")
                    encryptionAction?.invoke()
                    dialog.dismiss()
                    firstDialog?.dismiss()
                }
                //解锁逻辑
                if (state == 1) {
                    val result = PdfBoxUtils.checkPwd(path, pwd, uri)
                    LogEx.logDebug("checkPwd", "result=$result")
                    if (result) {
                        PdfBoxUtils.clearPassword(path, pwd)
                        toast("clear Encryption")
                        encryptionAction?.invoke()
                        dialog.dismiss()
                        firstDialog?.dismiss()
                    } else {
                        binding.tvErrorTip.visibility = View.VISIBLE
                    }
                }
            } else {
                //验证密码逻辑
                val result = PdfBoxUtils.checkPwd(path, pwd, uri)
                if (!result) {
                    binding.tvErrorTip.visibility = View.VISIBLE
                    return@setOnClickListener
                }
                dialog.dismiss()
                firstDialog?.dismiss()
                verificationAction?.invoke(pwd)
            }

        }
        binding.ivEye.setOnClickListener {

            if (binding.edit.transformationMethod == null) {
                // 隐藏密码
                binding.edit.transformationMethod = PasswordTransformationMethod()
                binding.ivEye.setImageResource(R.mipmap.weishuru)
            } else {
                // 显示密码
                binding.edit.transformationMethod = null
                binding.ivEye.setImageResource(R.mipmap.yishuru)
            }
        }

    }
}