using UnityEngine;

namespace Nox.Game {
    public enum DayPhase {
        Midnight,
        Dawn,
        Morning,
        Afternoon,
        Dusk,
        Night
    }

    public class TimeHandler {
        private readonly AdventureSettings adventureSettings;
        private readonly AdventureData adventureData;

        private float localTime;

        private static readonly (float start, DayPhase phase)[] PhaseThresholds = {
            (0.00f, DayPhase.Midnight),
            (0.05f, DayPhase.Night),
            (0.17f, DayPhase.Dawn),
            (0.25f, DayPhase.Morning),
            (0.50f, DayPhase.Afternoon),
            (0.75f, DayPhase.Dusk),
            (0.90f, DayPhase.Night),
        };

        public TimeHandler(AdventureSettings adventureSettings, AdventureData adventureData) {
            this.adventureSettings = adventureSettings;
            this.adventureData = adventureData;
            localTime = adventureData.currentTime * adventureSettings.dayLength;
        }

        public void Tick() {
            if (!adventureData.isPartyMoving) return;

            localTime += Time.deltaTime;

            if (localTime >= adventureSettings.dayLength) {
                localTime -= adventureSettings.dayLength;
                adventureData.currentDay++;
            }

            adventureData.currentTime = localTime / adventureSettings.dayLength;
            adventureData.currentDayPhase = GetPhase(adventureData.currentTime);
        }

        private static DayPhase GetPhase(float t) {
            var phase = DayPhase.Midnight;
            foreach (var (start, p) in PhaseThresholds) {
                if (t >= start) phase = p;
                else break;
            }
            return phase;
        }
    }
}
