package com.swago.user

import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.marginBottom
import com.gyf.immersionbar.ImmersionBar
import com.swago.baseswago.dialog.BaseXDFragment
import com.swago.baseswago.util.AppContext
import com.swago.baseswago.util.KeyboardUtils
import com.swago.baseswago.util.NoDoubleClickListener
import com.swago.user.databinding.DialogEditBinding

/**
 *@date 2022/3/12 17:09
 *description:
 */
class EditDialog : BaseXDFragment<DialogEditBinding>() {

    // 1 昵称  2 签名

    private var content:String = ""
    var callback:((content:String)->Unit)? = null

    companion object{
        fun newInstance(type:Int,content: String): EditDialog {
            val args = Bundle()
            args.putInt("type",type)
            args.putString("content",content)
            val fragment = EditDialog()
            fragment.arguments = args
            return fragment
        }
    }

    init {
        setCanCancel(false)
        setGravity(Gravity.BOTTOM)
        setDimAmount(0.5f)
    }

    override fun initOther() {
        binding.tvCancel.setOnClickListener(object:NoDoubleClickListener(){
            override fun onClick() {
                KeyboardUtils.hideSoftInput(binding.etContent)
                dismissAllowingStateLoss()
            }
        })

        binding.tvConfirm.setOnClickListener(object:NoDoubleClickListener(){
            override fun onClick() {
                KeyboardUtils.hideSoftInput(binding.etContent)
                content = binding.etContent.text.toString().trim()
                callback?.invoke(content)
                dismissAllowingStateLoss()
            }
        })

        activity?.let {
            KeyboardUtils.registerSoftInputChangedListener(it.window, listener)
        }

        arguments?.let {
            content = it.getString("content","")
            binding.etContent.setText(content)
            binding.etContent.setSelection(content.length)
            binding.etContent.requestFocus()
            when(it.getInt("type",1)){
                1 -> {
                    binding.tvTitle.text = AppContext.getContext().resources.getString(R.string.nickname)
                }
                2 -> {
                    binding.tvTitle.text = AppContext.getContext().resources.getString(R.string.sign)
                }
            }
            KeyboardUtils.showSoftInput()
        }
    }

    override fun initLiveData() {
    }

    override fun onDestroyView() {
        activity?.let {
            KeyboardUtils.unregisterSoftInputChangedListener(it.window)
        }
        super.onDestroyView()
    }

    var listener = KeyboardUtils.OnSoftInputChangedListener {
        val params = binding.clRoot.layoutParams  as ConstraintLayout.LayoutParams
        params.bottomMargin = it
        binding.clRoot.layoutParams = params
    }
}