using UnityEngine;
using VOID.Generic.Objects.Abstract;
using VOID.Generic.Objects.Unit.Actions.Exceptions;

namespace VOID.Generic.Objects.Unit.Actions
{
    public class RotateAction : AbstractAction
    {
        private readonly UnitObject _unit;
        private readonly float _targetYaw;
        
        public RotateAction(UnitObject unit, float targetYaw)
        {
            _unit = unit;
            _targetYaw = targetYaw;
        }

        public RotateAction(UnitObject unit, Vector3 lookAt)
        {
            _unit = unit;
            _targetYaw = Vector3.SignedAngle(
                Vector3.forward,
                Vector3.Scale(lookAt - unit.transform.position, new Vector3(1,0,1)),
                Vector3.up);
        }

        public RotateAction(UnitObject unit, AbstractObject lookAt) : this(unit, lookAt.transform.position) { }

        public override bool IsInRange() => true;
        public override bool CanSkipQueue() => true;

        protected override void OnEndIt() { }

        protected override void OnCancelIt() { }
        
        public override void CanDoIt()
        {
            Check(
                state == ActionState.Ready,
                UnitActionErrorType.ActionStateIsNotReady);
        }

        protected override void OnDoIt()
        {
            BeforePerform();
            var targetRotation = _unit.transform.rotation.eulerAngles;
            targetRotation.y = _targetYaw;
            _unit.transform.rotation = Quaternion.Euler(targetRotation);
            AfterPerform();
            EndIt();
        }
    }
}