using System;

namespace JohnsonUtils.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;
        }
    }
}