package com.base.easyfilemanager.view

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import com.base.easyfilemanager.R
import com.base.easyfilemanager.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
    }
}