using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Markup.Xaml;

namespace InABox.Avalonia.Components.TimeSelector;

public partial class TimeSelectorView : UserControl
{
    public TimeSelectorView()
    {
        InitializeComponent();
    }

    protected override void OnInitialized()
    {
        base.OnInitialized();

        (DataContext as TimeSelectorViewModel)!.GetTime = GetTime;
    }

    private TimeSpan? GetTime()
    {
        var hourSelector = TimePicker.GetTemplateChildren().OfType<DateTimePickerPanel>().FirstOrDefault(x => x.Name == "PART_HourSelector");
        var minuteSelector = TimePicker.GetTemplateChildren().OfType<DateTimePickerPanel>().FirstOrDefault(x => x.Name == "PART_MinuteSelector");
        var periodSelector = TimePicker.GetTemplateChildren().OfType<DateTimePickerPanel>().FirstOrDefault(x => x.Name == "PART_PeriodSelector");

        var hr = hourSelector!.SelectedValue;
        var min = minuteSelector!.SelectedValue;
        var per = periodSelector!.SelectedValue;

        hr = per == 1 ? (hr == 12) ? 12 : hr + 12 : per == 0 && hr == 12 ? 0 : hr;

        return new(hr, min, 0);
    }
}