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

namespace Game;

[SceneTree]
public partial class DaySchedule : PanelContainer
{
    private TimeSlot _currentTimeSlot;

    [Export]
    private int _hoursInDay = 6;

    private int _newTimeSlot;

    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()
    {
        _currentTimeSlot?.EndMeeting();

        if (_newTimeSlot >= GetTimeSlots().Count)
        {
            EndDay();
            return;
        }

        _currentTimeSlot = GetTimeSlots()[_newTimeSlot];
        _currentTimeSlot.StartMeeting();

        _newTimeSlot += 1;
    }

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

        _currentTimeSlot = GetTimeSlots().First();

        _currentTimeSlot.StartMeeting();
        _newTimeSlot += 1;

        EventBus.DayStarted?.Invoke();
    }

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

        _currentTimeSlot = null;
        _newTimeSlot = 0;

        ProgressTimer.Stop();
        CurrentTimeLine.Stop();
    }

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