using System;
using UnityEngine;
using VContainer.Unity;

namespace Minesweeper.Core
{
    public sealed class GameTimerService : IGameTimerService, ITickable
    {
        private readonly IGamePauseService pauseService;
        private readonly IGameStateService gameStateService;
        private int lastReportedSeconds = -1;

        public GameTimerService(IGameStateService gameStateService, IGamePauseService pauseService)
        {
            this.gameStateService = gameStateService;
            this.pauseService = pauseService;
        }

        public event Action<float> TimeChanged;

        public float ElapsedSeconds { get; private set; }

        public void Tick()
        {
            if (gameStateService.Current != GameState.Playing || pauseService.IsPaused)
            {
                return;
            }

            ElapsedSeconds += Time.deltaTime;
            var seconds = Mathf.FloorToInt(ElapsedSeconds);
            if (seconds == lastReportedSeconds)
            {
                return;
            }

            lastReportedSeconds = seconds;
            TimeChanged?.Invoke(ElapsedSeconds);
        }

        public void Reset()
        {
            ElapsedSeconds = 0f;
            lastReportedSeconds = -1;
            TimeChanged?.Invoke(ElapsedSeconds);
        }
    }
}
