using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;

enum AlarmClockState
{
    TICKING,
    FAST_TICKING,
    ALARMING,
    UNINITALIZED
}

public class AlarmClock : MonoBehaviour
{
    public static AlarmClock Instance;
    
    public TimeSpan timeUntilAlarm;
    private TimeSpan fastTickingTimeLeft = new TimeSpan(1, 0, 0);

    private AlarmClockState state;
    public AudioSource ticking;
    public AudioSource fastTicking;
    public AudioSource alarm;

    public float timeSkipMaxMul = 4f;
    
    private void Awake()
    {
        Instance = this;
    }

    // Start is called before the first frame update
    void Start()
    {
        reset();
    }

    public void reset()
    {
        timeUntilAlarm = new TimeSpan(8, 0, 0);
        state = AlarmClockState.UNINITALIZED;
    }

    // Update is called once per frame
    void Update()
    {
        checkState();

        if (state == AlarmClockState.ALARMING)
        {
            SleepDepth.drainInSecs(1);
        }
    }

    void checkState()
    {
        if (timeUntilAlarm == TimeSpan.Zero && state != AlarmClockState.ALARMING)
        {
            fastTicking.Pause();
            alarm.Play();
            state = AlarmClockState.ALARMING;
        } else if (timeUntilAlarm != TimeSpan.Zero &&
                   timeUntilAlarm <= fastTickingTimeLeft &&
                   state != AlarmClockState.FAST_TICKING)
        {
            alarm.Pause();
            ticking.Pause();
            fastTicking.Play();
            state = AlarmClockState.FAST_TICKING;
        }
        else if (timeUntilAlarm > fastTickingTimeLeft && state != AlarmClockState.TICKING)
        {
            alarm.Pause();
            fastTicking.Pause();
            ticking.Play();
            state = AlarmClockState.TICKING;
        }
    }

    public void updateTime()
    {
        TimeSpan delta = new TimeSpan((long) Mathf.Round(Timer.TEN_MIN.Ticks * Random.Range(1f, timeSkipMaxMul)));

        if (delta > timeUntilAlarm)
        {
            timeUntilAlarm = TimeSpan.Zero;
            return;
        }
        
        timeUntilAlarm -= delta;
    }
}
