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

namespace Actions {
    public class GrenadeAction : BaseAction {
        private const int maxThrowDistance = 7;

        [SerializeField] private Transform grenadeProjectilePrefab;

        protected override void Awake() {
            base.Awake();
            ActionPointsCost = 2;
            ActionName = "Grenade";
        }

        private void Update() {
            if (!IsActive) return;
        }

        public override void TakeAction(GridPosition gridPosition, Action onActionComplete) {
            Transform grenadeProjectileTransform = Instantiate(grenadeProjectilePrefab, Unit.GetWorldPosition(), Quaternion.identity);
            grenadeProjectileTransform.GetComponent<GrenadeProjectile>().Setup(gridPosition, OnGrenadeBehaviourComplete);
            ActionStart(onActionComplete);
        }

        public override List<GridPosition> GetValidActionGridPositionList() {
            List<GridPosition> validGridPositionList = new();
            GridPosition unitGridPosition = Unit.GridPosition;
            for (int x = -maxThrowDistance; x <= maxThrowDistance; x++) {
                for (int z = -maxThrowDistance; z <= maxThrowDistance; z++) {
                    GridPosition offsetGridPosition = new(x, z);
                    GridPosition testGridPosition = unitGridPosition + offsetGridPosition;

                    if (!LevelGrid.Instance.IsValidGridPosition(testGridPosition)) continue; //Only return valid grid positions
                    if (Mathf.Abs(x) + Mathf.Abs(z) > maxThrowDistance) continue; //Out of Range

                    validGridPositionList.Add(testGridPosition);
                }
            }

            return validGridPositionList;
        }

        protected override EnemyAIAction GetEnemyAIAction(GridPosition gridPosition) => new(gridPosition, 0);

        private void OnGrenadeBehaviourComplete() => ActionComplete();
    }
}