package com.all.pdfreader.pro.app.ui.dialog

import android.graphics.Color
import android.os.Bundle
import android.text.Html
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toDrawable
import androidx.fragment.app.DialogFragment
import com.all.pdfreader.pro.app.R
import com.all.pdfreader.pro.app.databinding.DialogPdfPasswordProtectionBinding
import com.all.pdfreader.pro.app.util.AppUtils.showKeyboard
import com.all.pdfreader.pro.app.util.FileUtils.isPdfPasswordCorrect
import java.io.File

class PdfPasswordProtectionDialogFragment(
    private val file: File,
    private val onOkClick: (String) -> Unit,
    private val onCancelClick: () -> Unit,
    private val isPrompt: Boolean = false
) : DialogFragment() {

    private lateinit var binding: DialogPdfPasswordProtectionBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        binding = DialogPdfPasswordProtectionBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun onStart() {
        super.onStart()
        isCancelable = false
        dialog?.window?.apply {
            // 去掉系统默认的背景 padding
            setBackgroundDrawable(Color.TRANSPARENT.toDrawable())
            // 设置宽度为全屏减去 16dp
            val margin = resources.getDimensionPixelSize(R.dimen.dialog_margin) // 16dp
            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()

        if (isPrompt) {
            binding.promptTv.visibility = View.VISIBLE
            val color = ContextCompat.getColor(requireContext(), R.color.text_color_lv1)
            binding.promptTv.setColoredPlaceholder(
                R.string.file_is_password_protected,
                file.name,
                color
            )
        } else {
            binding.promptTv.visibility = View.GONE
        }

        binding.cancelBtn.setOnClickListener {
            onCancelClick()
            dismiss()
        }
        binding.okBtn.setOnClickListener {
            val password = binding.etPassword.text.toString()
            if (password.isEmpty()) {
                binding.tilPassword.error = getString(R.string.password_not_empty)
                return@setOnClickListener
            }
            if (isPdfPasswordCorrect(requireActivity(), file, password)) {
                onOkClick(password)
                dismiss()
            } else {
                binding.tilPassword.error = getString(R.string.incorrect_password)
            }
        }
    }

    fun TextView.setColoredPlaceholder(
        @StringRes resId: Int,   // 字符串资源 ID
        placeholderText: String, // 要染色的占位符文字
        @ColorInt color: Int     // 颜色
    ) {
        val fullText = context.getString(resId, placeholderText)
        val start = fullText.indexOf(placeholderText)
        val end = start + placeholderText.length

        val spannable = SpannableString(fullText)
        spannable.setSpan(
            ForegroundColorSpan(color),
            start,
            end,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        text = spannable
    }

}