package com.zxhyis.toolss.ui.dialog

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.AppCompatTextView
import androidx.fragment.app.DialogFragment
import com.zxhyis.toolss.R
import com.zxhyis.toolss.logic.ClickCallBack
import com.zxhyis.toolss.logic.setOnClick
import com.zxhyis.toolss.logic.showToast

class FIleDialog : DialogFragment() {

    private lateinit var fileView: View

    private var clickCallBack: ClickCallBack? = null

    fun setCallBack(callBack: ClickCallBack) {
        clickCallBack = callBack
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        fileView = inflater.inflate(R.layout.dialog_create_file, container, false)
        return fileView
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val window = dialog?.window
        window?.setGravity(Gravity.CENTER)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        val windowManager = activity?.windowManager
        val display = windowManager?.defaultDisplay
        val lp = dialog?.window!!.attributes
        lp.width = (display?.width!! * 0.73).toInt() //设置宽度
        dialog?.window!!.attributes = lp

        val et = fileView.findViewById<AppCompatEditText>(R.id.et_name)
        var fileName = ""
        et.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) {

            }

            override fun afterTextChanged(s: Editable?) {
                fileName = s.toString()
            }

        })

        fileView.findViewById<AppCompatTextView>(R.id.tv_cancle).setOnClick(javaClass.simpleName) {
            dialog?.dismiss()
        }

        fileView.findViewById<AppCompatTextView>(R.id.tv_establish).setOnClick(javaClass.simpleName) {
            if (fileName != "") {
                clickCallBack?.clickBack(fileName)
                dismiss()
            } else {
                "The file name cannot be empty".showToast()
            }
        }


    }

}