package com.adealink.weparty.playmate.setting.dialog

import androidx.fragment.app.activityViewModels
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.commonui.widget.BottomDialogFragment
import com.adealink.weparty.playmate.R
import com.adealink.weparty.playmate.databinding.DialogPlaymateOrderTimeRangeBinding
import com.adealink.weparty.playmate.setting.viewmodel.OrderSettingViewModel
import com.adealink.weparty.playmate.viewmodel.PlaymateViewModelFactory
import com.adealink.weparty.util.TimeHour

class TimeRangeDialog : BottomDialogFragment(R.layout.dialog_playmate_order_time_range) {

    private val binding by viewBinding(DialogPlaymateOrderTimeRangeBinding::bind)

    private val viewModel by activityViewModels<OrderSettingViewModel> { PlaymateViewModelFactory() }

    override fun initViews() {
        super.initViews()
        binding.vTimeFrom.setEntries(
            TimeHour.entries.map { it.time() }
        )

        binding.vTimeTo.setEntries(
            TimeHour.entries.map { it.time() }
        )
//        updateTimeFromToIndex(viewModel.timeRangeLD.value)
        binding.btnConfirm.onClick {
            confirm()
        }
    }

    private fun updateTimeFromToIndex(timeRange: Pair<TimeHour, TimeHour>?) {
        timeRange?.first?.let {
            binding.vTimeFrom.currentIndex = it.ordinal
        }
        timeRange?.second?.let {
            binding.vTimeTo.currentIndex = it.ordinal
        }
    }

    override fun observeViewModel() {
        viewModel.timeRangeLD.observe(viewLifecycleOwner) {
            updateTimeFromToIndex(it)
        }
    }

    private fun confirm() {
        val fromTime = TimeHour.map(binding.vTimeFrom.currentIndex) ?: return
        val toTime = TimeHour.map(binding.vTimeTo.currentIndex) ?: return
        showLoading()
        viewModel.updateTimeRange(fromTime, toTime).observe(viewLifecycleOwner) { rlt ->
            dismissLoading()
            showToast(rlt)
            when (rlt) {
                is Rlt.Failed -> {
                    //Ntd.
                }

                is Rlt.Success -> {
                    dismiss()
                }
            }
        }
    }

}