use std::hash::Hash;

use crate::timeman::{self, Second};

pub struct TimeControlWidget<'f>
{
    manual_tick: &'f mut Second,
    auto_tick: &'f mut (bool, Second)
}

impl<'f> TimeControlWidget<'f>
{
    pub fn new(
        manual_tick: &'f mut Second,
        auto_tick: &'f mut (bool, Second))
    -> Self
    {
        Self {
            manual_tick,
            auto_tick
        }
    }

    pub fn show_ui(mut self,
        ui: &mut egui::Ui)
    -> egui::InnerResponse<Option<Second>>
    {
        egui::Frame::new().show(ui, |frame| {
            frame.set_max_width(224.0);
            frame.vertical(|vertical| {
                let ret = self.show_manual(vertical);
                ret
            }).inner
        })
    }

    const TICK_OPTIONS: [(&'static str, Second);10] = [
        ("1 second", 1),
        ("5 seconds", 5),
        ("30 seconds", 30),
        ("1 minute", timeman::MINUTE),
        ("5 minutes", 5 * timeman::MINUTE),
        ("30 minutes", 30 * timeman::MINUTE),
        ("1 hour", timeman::HOUR),
        ("1 day", timeman::DAY),
        ("5 days", 5 * timeman::DAY),
        ("30 days", 30 * timeman::DAY)
    ];

    fn tick_selector_combobox<T: Hash>(
        ui: &mut egui::Ui,
        id_salt: T,
        selected: Second)
    -> Second
    {
        let selected_value = Self::TICK_OPTIONS.iter().find(|v| { v.1 == selected }).unwrap();
        egui::ComboBox::new(id_salt, "")
            .selected_text(selected_value.0)
            .show_ui(ui, 
        |combobox| {
            let mut ret = selected;
            for entry in Self::TICK_OPTIONS {
                combobox.selectable_value(&mut ret, entry.1, entry.0);
            }
            ret
        }).inner.unwrap_or(selected)
    }

    fn show_manual(&mut self,
        ui: &mut egui::Ui)
    -> Option<Second>
    {

        ui.horizontal(|horizontal| {
            horizontal.checkbox(&mut self.auto_tick.0, "Auto Advance ");
            self.auto_tick.1 = Self::tick_selector_combobox(horizontal, "auto-tick-combobox", self.auto_tick.1);
        });
        ui.shrink_width_to_current();
        ui.horizontal(|horizontal| {
            let mut tick: Option<Second> = None;
            if horizontal.button("Manual Advance").clicked() {
                tick = Some(*self.manual_tick);
            }
            *self.manual_tick = Self::tick_selector_combobox(horizontal, "manual-tick-combobox", *self.manual_tick);

            tick
        }).inner
    }
}
