using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using RPG_Fight_Test.Assets.Scripts.Creatures;
using UnityEngine;
using UnityEngine.UI;

public class RoundManager : MonoBehaviour {

    [SerializeField] Button executeRoundButton;
    private List<Creature> combatants;
    int round;

    private bool executing = false;

    private void Start() {
        executeRoundButton.onClick.AddListener(ExecuteRound);
    }

    private void ExecuteRound() {
        executing = true;
        executeRoundButton.interactable = false;
        foreach (Creature c in combatants) {
            StartCoroutine(c.GetFirstAction().PerformAction());
        }
        round++;
    }

    private void FixedUpdate() {
        if (executing) {
            foreach (Creature c in combatants) {
                c.CurrentPos = Vector3Int.RoundToInt(c.gameObject.transform.position);
            }
        }
    }

    internal void StartFirstRound(List<Creature> combatants) {
        this.combatants = combatants;
        round = 1;
        MakeDecisions();
    }

    internal void SetupNextRound() {
        this.combatants = combatants.FindAll(c => c.IsCreatureAlive);
        MakeDecisions();
    }

    private void MakeDecisions() {
        foreach (Creature creature in combatants) {
            if (creature.IsHumanControlled()) {
                CameraManager.GetInstance().FocusOnGameObject(creature.gameObject);

                // TODO REMOVE testing
                if (creature.name.Equals("Human2")) {
                    MoveAction ma = new MoveAction();
                    ma.SetTargetPosition(new Vector3(2.5f, -27.5f, 0f));
                    ma.SetStartPosition(creature.CurrentPos);
                    ma.SetCreatureToMove(creature);
                    creature.SetFirstAction(ma);
                } else {
                    creature.SetFirstAction(new AttackAction(combatants[0]));
                }
                creature.SetSecondAction(new AttackAction(combatants[0])); // TODO REMOVE testing
                // Wait for human decision
            } else {
                ((Skeleton)creature).DecideActions(combatants); // FIXME Skeleton won't work.. need to be more general
                // AI make decision
            }
        }

        if (CheckIfAllCombatantsHaveTheirActions()) {
            executeRoundButton.interactable = true;
        }
    }

    private bool CheckIfAllCombatantsHaveTheirActions() {
        return combatants.All(c => c.HasFirstAction() && c.HasSecondAction());
    }
}
