package com.all.pdfreader.pdf.reader.ui.dialog

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.graphics.drawable.toDrawable
import androidx.fragment.app.DialogFragment
import com.all.pdfreader.pdf.reader.R
import com.all.pdfreader.pdf.reader.databinding.DialogPdfRemovePasswordBinding
import com.all.pdfreader.pdf.reader.util.AnalyticsUtils
import com.all.pdfreader.pdf.reader.util.AppUtils.showKeyboard
import com.all.pdfreader.pdf.reader.util.FileUtils.isPdfPasswordCorrect
import com.all.pdfreader.pdf.reader.util.ToastUtils
import java.io.File

class PdfRemovePasswordDialog() : DialogFragment() {

    companion object {
        private const val ARG_FILE_PATH = "arg_file_path"

        fun newInstance(filePath: String): PdfRemovePasswordDialog {
            val fragment = PdfRemovePasswordDialog()
            val args = Bundle()
            args.putString(ARG_FILE_PATH, filePath)
            fragment.arguments = args
            return fragment
        }
    }

    var onOkClick: ((password: String) -> Unit)? = null

    private lateinit var binding: DialogPdfRemovePasswordBinding

    private val filePath: String
        get() = arguments?.getString(ARG_FILE_PATH) ?: ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 系统恢复时直接关闭，防止 crash
        if (savedInstanceState != null) {
            dismissAllowingStateLoss()
            return
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        if (savedInstanceState != null) return null
        binding = DialogPdfRemovePasswordBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onStart() {
        super.onStart()
        isCancelable = false
        dialog?.window?.apply {
            setBackgroundDrawable(Color.TRANSPARENT.toDrawable())
            val margin = resources.getDimensionPixelSize(R.dimen.dialog_margin)
            val width = resources.displayMetrics.widthPixels - margin * 2
            setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT)
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.etPassword.showKeyboard()
        setupListeners()
        AnalyticsUtils.logEvent(AnalyticsUtils.Event.UNLOCK_TK_SHOW)
    }

    private fun setupListeners() {
        binding.cancelBtn.setOnClickListener {
            dismiss()
        }

        binding.okBtn.setOnClickListener {
            val password = binding.etPassword.text.toString()
            val file = File(filePath)
            if (isPdfPasswordCorrect(requireActivity(), file, password)) {
                onOkClick?.invoke(password)
                dismiss()
            } else {
                binding.tilPassword.error = getString(R.string.incorrect_password)
            }
        }
    }
}
