package kr.co.vividnext.sodalive.dialog

import android.app.TimePickerDialog
import android.content.Context
import android.widget.TimePicker

class SodaLiveTimePickerDialog(
    context: Context,
    themeResId: Int,
    private val onTimeSetListener: OnTimeSetListener,
    hourOfDay: Int,
    minute: Int,
    is24HourView: Boolean
) : TimePickerDialog(context, themeResId, null, hourOfDay, minute, is24HourView) {
    private var timePicker: TimePicker? = null

    init {
        this.setTitle("Select Time")
        setOnShowListener {
            timePicker = window?.findViewById(
                context.resources.getIdentifier(
                    "android:id/timePicker",
                    null,
                    null
                )
            )
            timePicker?.apply {
                setIs24HourView(is24HourView)
                setOnTimeChangedListener { _, _, minute ->
                    // Snap minute to nearest quarter (0, 15, 30, 45)
                    val snappedMinute = minute / 15 * 15
                    if (snappedMinute != minute) {
                        this.minute = snappedMinute
                    }
                }
            }
            getButton(BUTTON_POSITIVE).setOnClickListener {
                timePicker?.let { picker ->
                    onTimeSetListener.onTimeSet(picker, picker.hour, picker.minute)
                }
                dismiss()
            }
        }
    }
}
