package com.zxhy.simplefilesmanager.simpledialog

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import com.zxhy.simplefilesmanager.R
import com.zxhy.simplefilesmanager.databinding.DialogFileNewRenameBinding

object SimpleFileDialog {
    fun Context.showSimpleFileDialog(
        name: String = "",
        nameAction: (name: String) -> Unit
    ): AlertDialog {

        val binding = DialogFileNewRenameBinding.inflate(LayoutInflater.from(this))
        val dialog = AlertDialog.Builder(this).setView(binding.root).create()
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()

        //修改dialog的尺寸
        val lp = dialog.window?.attributes
        lp?.width = this.resources.getDimensionPixelOffset(R.dimen.dp_280)
        lp?.height = ViewGroup.LayoutParams.WRAP_CONTENT
        dialog.window?.attributes = lp
        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)

        if (name.isNotEmpty()) {
            binding.edit.setText(name)
        }

        binding.tvSure.setOnClickListener {
            val text = binding.edit.text.toString()
            if (text.isEmpty() or text.isBlank()) {
                return@setOnClickListener
            }
            nameAction.invoke(text)
            dialog.dismiss()
        }
        binding.ivCancel.setOnClickListener {
            dialog.dismiss()
        }

        return dialog
    }
}