using UnityEngine;
using VOID.Generic.Dict;
using VOID.Generic.Objects.Item;
using VOID.Generic.Objects.Item.Events;
using VOID.Generic.Objects.Unit.Actions.Exceptions;
using VOID.Generic.Util;

namespace VOID.Generic.Objects.Unit.Actions
{
    public class MoveItemAction : AbstractAction
    {
        private readonly UnitObject _unit;
        private readonly ItemObject _item;
        private readonly Vector3 _toPosition;
        
        public MoveItemAction(UnitObject unit, ItemObject item, Vector3 toPosition)
        {
            _unit = unit;
            _item = item;
            _toPosition = toPosition;
        }

        public override bool IsInRange()
        {
            return RangeUtil.IsInRange(_unit, _item, _unit.unitData.takeRange)
                && RangeUtil.IsInRange(_item, _toPosition, _unit.unitData.takeRange*2);
        }

        protected override void OnEndIt() {}

        protected override void OnCancelIt() {}

        public override void CanDoIt()
        {
            Check(
                state == ActionState.Ready,
                UnitActionErrorType.ActionStateIsNotReady);
            if (_unit.basicState.turnManager)
            {
                Check(
                    _unit.unitState.isSelfTurn,
                    UnitActionErrorType.UnitSelfTurnNotActive);
                Check(
                    _unit.unitData.currentResources.actionPoints >= 1,
                    UnitActionErrorType.UnitNotEnoughActionPoints);
            }
            Check(
                _item.itemData.canBeMoved,
                UnitActionErrorType.ItemIsNotMovable);
            Check(
                _unit.unitState.isControllable,
                UnitActionErrorType.UnitStateIsNotControllable);
            Check(
                IsInRange(),
                UnitActionErrorType.NotInRange);
        }

        protected override void OnDoIt()
        {
            if (_unit.basicState.turnManager)
                _unit.unitData.UseResource(UnitResourceType.ActionPoints, 1);
            
            var moveItemEvent = new MoveItemEvent
            {
                unit = _unit,
                item = _item,
                fromPosition = _item.transform.position,
                toPosition = _toPosition,
            };

            _item.itemEvents.onMovedBefore.Invoke(moveItemEvent);
            _unit.unitEvents.onMoveItemBefore.Invoke(moveItemEvent);

            _unit.OrderInstantly(new RotateAction(_unit, _item));
            BeforePerform();
            
            Check(_item.Move(_toPosition), UnitActionErrorType.ItemIsNotMovable);
            
            _item.itemEvents.onMovedAfter.Invoke(moveItemEvent);
            _unit.unitEvents.onMoveItemAfter.Invoke(moveItemEvent);
            
            AfterPerform();
            EndIt();
        }
    }
}