package com.base.pdfreader2.ui.view

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.core.widget.addTextChangedListener
import com.base.pdfreader2.R
import com.base.pdfreader2.databinding.DialogDocumentRenameBinding
import com.base.pdfreader2.utils.KotlinExt.toFormatTime2
import com.base.pdfreader2.utils.ToastUtils.toast
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog

object NameDialog {

    /**
     * 重命名
     */
    fun Context.showDocumentRenameDialog(
        name: String? = null,
        okAction: ((newName: String) -> Unit)? = null,
        dismissAction: (() -> Unit)? = null
    ) {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val binding = DialogDocumentRenameBinding.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

        binding.edit.addTextChangedListener {
            binding.tvOk.isEnabled = !it.isNullOrEmpty()
        }

        val tempName = "Split_" + System.currentTimeMillis().toFormatTime2()
        binding.edit.setText(name ?: tempName)
        if (name == null) {
            binding.edit.selectAll()
        } else {
            val nameS = name.split(".")[0]
            binding.edit.setSelection(0, nameS.length)
        }
        binding.edit.requestFocus()

        binding.tvCancel.setOnClickListener {
            dialog.dismiss()
        }
        binding.tvOk.setOnClickListener {
            dialog.dismiss()

            val newName = binding.edit.text.toString()
            if (newName.isEmpty()) {
                toast("name can't be empty!")
                return@setOnClickListener
            }
            okAction?.invoke(newName)
        }
        dialog.setOnDismissListener {
            dismissAction?.invoke()
        }
    }
}