using System;
using System.Collections.Generic;
using System.Linq;
using Grid;
using UnityEngine;

namespace Actions {
    public abstract class BaseAction : MonoBehaviour {
        protected bool IsActive;
        private Action onActionComplete;
        public Unit Unit { get; private set; }
        public int ActionPointsCost { get; protected set; } = 1;
        public string ActionName { get; protected set; }

        public static event EventHandler OnAnyActionStarted;
        public static event EventHandler OnAnyActionEnded;

        protected virtual void Awake() => Unit = GetComponent<Unit>();

        public abstract void TakeAction(GridPosition gridPosition, Action onActionComplete);

        public bool IsValidActionGridPosition(GridPosition gridPosition) => GetValidActionGridPositionList().Contains(gridPosition);

        public abstract List<GridPosition> GetValidActionGridPositionList();

        protected void ActionStart(Action actionComplete) {
            IsActive = true;
            onActionComplete = actionComplete;
            OnAnyActionStarted?.Invoke(this, EventArgs.Empty);
        }

        protected void ActionComplete() {
            IsActive = false;
            onActionComplete();
            OnAnyActionEnded?.Invoke(this, EventArgs.Empty);
        }

        public EnemyAIAction GetBestEnemyAIAction() {
            List<EnemyAIAction> enemyAIActionList = GetValidActionGridPositionList().Select(GetEnemyAIAction).ToList();
            if (enemyAIActionList.Count <= 0) return null; // No possible Enemy AI Actions
            enemyAIActionList.Sort((a, b) => b.ActionValue - a.ActionValue);
            return enemyAIActionList[0];
        }

        protected abstract EnemyAIAction GetEnemyAIAction(GridPosition gridPosition);
    }
}