package com.example.base.dialog

import android.app.Dialog
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.View
import android.widget.TextView
import android.widget.TimePicker
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import com.example.base.R
import com.example.base.extensions.getHHMM
import com.example.base.extensions.onClick
import org.jetbrains.anko.find
import java.util.Calendar

/**
 * 这是一个时间选择控件
 */

class TimeDialogFragment : DialogFragment() {

    private var mCurrentTime: Long = 0

    private var mOnSelectedListener: ((time: Long) -> Unit)? = null



    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

        mCurrentTime = arguments?.getLong(ARG_TIME, System.currentTimeMillis()) ?: 0


        val v = View.inflate(context, R.layout.mvvm_dialog_time, null)
        initView(v)

        v.find<TextView>(R.id.tv_ok).onClick {
            mOnSelectedListener?.invoke(mCurrentTime)
            dismiss()
        }
        v.find<TextView>(R.id.tv_cancel).onClick {
            dismiss()
        }

        val mDialog = AlertDialog.Builder(requireContext())
        mDialog.setView(v)

        return mDialog.create()
    }

    override fun onStart() {
        super.onStart()
        val dm = DisplayMetrics()
        requireActivity().windowManager.defaultDisplay.getMetrics(dm)
        dialog!!.window!!.setLayout(
            (dm.widthPixels * 0.8).toInt(),
            dialog!!.window!!.attributes.height
        )
    }

    fun setOnSelectedListener(listener: ((time: Long) -> Unit)) {
        mOnSelectedListener = listener
    }

    private fun initView(view: View) {

        val tvTime = view.findViewById<TextView>(R.id.tvTime)
        val timePicker = view.findViewById<TimePicker>(R.id.timePicker)
        timePicker.setIs24HourView(true)
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = mCurrentTime
        tvTime.text = mCurrentTime.getHHMM()

        timePicker.setOnTimeChangedListener { _, hourOfDay, minute ->
            calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
            calendar.set(Calendar.MINUTE, minute)
            val time = calendar.time.time
            tvTime.text = time.getHHMM()
            mCurrentTime = time
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mOnSelectedListener = null
    }

    companion object {
        private const val ARG_TIME = "time"
        fun newInstance(time: Long = System.currentTimeMillis()): TimeDialogFragment {
            val arg = Bundle()
            arg.putLong(ARG_TIME, time)
            val fragment = TimeDialogFragment()
            fragment.arguments = arg
            return fragment
        }
    }

}













