using System.Collections.Generic;
using System.Linq;
using Godot;

namespace Game;

[SceneTree]
public partial class DaySchedule : PanelContainer
{
    private int _currentSlot;

    [Export]
    private int _hoursInDay = 6;

    public override void _Ready()
    {
        TimeSlotContainer.GetChildren().ToList().ForEach(child => child.QueueFree());

        for (var i = 0; i < _hoursInDay; i++)
        {
            var timeSlot = Instantiator.Instantiate<TimeSlot>();

            TimeSlotContainer.AddChild(timeSlot);
        }

        ProgressTimer.Timeout += OnNewMeetingStarts;

        SetupCurrentTimeLine();
    }

    private void SetupCurrentTimeLine()
    {
        var timeSlot = Instantiator.Instantiate<TimeSlot>();
        CurrentTimeLine.Speed = (float)(timeSlot.Size.Y / ProgressTimer.WaitTime);
    }

    private void OnNewMeetingStarts()
    {
        if (_currentSlot >= GetTimeSlots().Count)
        {
            EndDay();
            return;
        }

        GetTimeSlots()[_currentSlot].StartMeeting();

        _currentSlot += 1;
    }

    public void StartDay()
    {
        ProgressTimer.Start();
        CurrentTimeLine.Start();

        GetTimeSlots().First().StartMeeting();
        _currentSlot += 1;

        EventBus.DayStarted?.Invoke();
    }

    public void EndDay()
    {
        GD.Print("The DAY was EXECUTED!");
        ProgressTimer.Stop();
        CurrentTimeLine.Stop();
    }

    private List<TimeSlot> GetTimeSlots()
    {
        return [.. TimeSlotContainer.GetChildren().OfType<TimeSlot>()];
    }
}
