using Intrepid.Theatre.Curtain;
using Intrepid.Utilities;
using UnityEngine;

namespace Intrepid.Core.Curtain.Actions
{
    public class CurtainFadeClosingAction : AbstractCurtainAction
    {
        [SerializeField] private float timeToClose = 2.5f;
        [SerializeField] private CanvasGroup canvasGroup;
        
        public override bool IsFinished()
        {
            return canvasGroup.alpha >= 1;
        }
        
        private Timer Timer { get; } = new();

        private void Update()
        {
            if (!Timer.IsRunning) return;
            Timer.Update(Time.deltaTime);
            if (!Timer.Check(timeToClose))
            {
                canvasGroup.alpha = Mathf.Clamp01((float)Timer.RunningTime / timeToClose);
                return;
            }
            StateMachine.RaiseCommand(CurtainCommandType.Done);
        }

        public override void Setup()
        {
            Timer.Start();
            canvasGroup.alpha = 0f;
        }

        public override void TearDown()
        {
            Timer.Stop();
            canvasGroup.alpha = 1f;
        }
    }
}