using System;

namespace Common
{
    public class Timer
    {
        public event Action OnTimeOver;
    
        public bool IsRunning { get; private set; }

        public float CurrentTime { get; private set; }

        private readonly float startingTime;
        private readonly bool isCountDown;
        private bool isEnabled;

        public Timer(float startTime, bool countDown = true)
        {
            IsRunning = false;
            isEnabled = true;
            startingTime = startTime;
            isCountDown = countDown;
            Init();
        }

        private void Init()
        {
            CurrentTime = startingTime;
        }

        public void Tick(float dt)
        {
            if (!IsRunning || !isEnabled) return;
            
            CurrentTime += isCountDown ? -dt : dt;

            if (CurrentTime < 0)
            {
                CurrentTime = 0;
                IsRunning = false;
                isEnabled = false;
                OnTimeOver?.Invoke();
            }
        }

        public void Reset()
        {
            isEnabled = true;
            CurrentTime = isCountDown ? startingTime : 0;
        }
        
        public void Start() => IsRunning = true;
        public void Pause() => IsRunning = false;
        public void Stop()
        {
            IsRunning = false;
            isEnabled = false;
            CurrentTime = 0;
        }
    }
}