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

import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.graphics.drawable.toDrawable
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.activityViewModels
import com.all.pdfreader.pro.app.R
import com.all.pdfreader.pro.app.databinding.DialogRenameFileBinding
import com.all.pdfreader.pro.app.model.RenameType
import com.all.pdfreader.pro.app.room.entity.BookmarkEntity
import com.all.pdfreader.pro.app.util.AppUtils.showKeyboard
import com.all.pdfreader.pro.app.util.FileUtils
import com.all.pdfreader.pro.app.util.ToastUtils
import com.all.pdfreader.pro.app.viewmodel.PdfViewModel
import java.io.File

class RenameDialogFragment(
    private val type: RenameType,
    private val bookmark: BookmarkEntity? = null,
    private val name: String? = null,
    private val onOkClick: (BookmarkEntity) -> Unit = {},
    private val onOkClickString: (String) -> Unit = {}
) : DialogFragment() {

    private lateinit var binding: DialogRenameFileBinding
    private val viewModel: PdfViewModel by activityViewModels()

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

    override fun onStart() {
        super.onStart()
        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)
        when (type) {
            RenameType.FILE -> {
                viewModel.pdfDocument.value?.let {
                    initView(it.fileName)
                    setupOnClick(it.fileName, it.filePath, null)
                } ?: run {
                    showToast(getString(R.string.file_not))
                    dismiss()
                }
            }

            RenameType.BOOKMARK -> {
                bookmark?.let {
                    initView(it.label)
                    setupOnClick(it.label, it.filePath, it)
                } ?: run {
                    showToast(getString(R.string.file_not))
                    dismiss()
                }
            }

            RenameType.NAME -> {
                name?.let {
                    initView(it)
                    setupOnClick(it, it, null)
                }?:run {
                    dismiss()
                }
            }
        }
    }

    private fun initView(name: String) {
        binding.etName.showKeyboard()
        binding.etName.setText(FileUtils.removeFileExtension(name))
        // 保持光标在末尾
        binding.etName.setSelection(binding.etName.text?.length ?: 0)
    }

    private fun setupOnClick(oldName: String, filePath: String, bookmark: BookmarkEntity?) {
        binding.cancelBtn.setOnClickListener {
            dismiss()
        }
        binding.okBtn.setOnClickListener {
            when (type) {
                RenameType.FILE -> {
                    val text = binding.etName.text.toString()
                    if (validateEnter(text, oldName, filePath)) {
                        viewModel.renamePdf(filePath, text)
                        dismiss()
                    }
                }

                RenameType.BOOKMARK -> {
                    val text = binding.etName.text.toString()
                    if (validateEnter(text, oldName, filePath)) {
                        val new = bookmark?.copy(label = text)!!
                        viewModel.updateBookmark(new)
                        onOkClick(new)
                        dismiss()
                    }
                }

                RenameType.NAME -> {
                    val text = binding.etName.text.toString()
                    if (validateEnter(text, oldName, filePath)) {
                        onOkClickString(text)
                        dismiss()
                    }
                }
            }

        }
        binding.etName.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                binding.tilName.error = null
            }

            override fun afterTextChanged(s: Editable?) {}
        })
    }

    private fun validateEnter(name: String, oldName: String, filePath: String): Boolean {
        // 不允许为空
        if (name.isBlank()) {
            binding.tilName.error = getString(R.string.name_not_empty)
            return false
        }

        // 含有非法字符
        val invalidChars = "[/\\\\:*?\"<>|.]".toRegex()
        if (invalidChars.containsMatchIn(name)) {
            binding.tilName.error = getString(R.string.name_invalid_chars)
            return false
        }

        when (type) {
            //只有修改文件名称时，才进行以下判断
            RenameType.FILE -> {
                if (name.length > 255) {
                    binding.tilName.error = getString(R.string.name_too_long)
                    return false
                }
                // 名字未做修改（因展示的时候去掉了扩展名，则判断的时候也去掉）
                if (name == FileUtils.removeFileExtension(oldName)) {
                    binding.tilName.error = getString(R.string.name_not_changed)
                    return false
                }
                // 与现有文件重名
                val parentDir = File(filePath).parentFile
                if (parentDir != null && File(parentDir, name).exists()) {
                    binding.tilName.error = getString(R.string.name_already_exists)
                    return false
                }
            }

            RenameType.BOOKMARK -> {
                if (name.length > 50) {
                    binding.tilName.error = getString(R.string.name_too_long)
                    return false
                }
                if (name == oldName) {
                    binding.tilName.error = getString(R.string.name_not_changed)
                    return false
                }
            }

            RenameType.NAME -> {
                if (name.length > 50) {
                    binding.tilName.error = getString(R.string.name_too_long)
                    return false
                }
                if (name == oldName) {
                    binding.tilName.error = getString(R.string.name_not_changed)
                    return false
                }
            }
        }

        // 禁止开头/结尾空格
        if (name != name.trim()) {
            binding.tilName.error = getString(R.string.name_start_end_space)
            return false
        }

        return true
    }

    private fun showToast(message: String) {
        ToastUtils.show(requireActivity(), message)
    }
}