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

[RequireComponent(typeof(TurnRegister))]
public class TurnActor : MonoBehaviour
{
    public int TurnOrderPriority = 1;
    public bool WaitsForInput = false;
    private List<TurnAction> plans = new List<TurnAction>();

    public virtual void Start()
    {
        if(name != "Player(Clone)")
            TurnBasedGameLoop.instance.AddActorToGame(this);
    }

    public TurnAction GetAction()
    {
        if (ShouldSkip())
            return new ActionWait();

        BuildPlans();
        FilterPlansForPriority();
        return ChooseRandomPlanFromList();
    }

    protected virtual bool ShouldSkip()
    {
        return false;
    }

    private void BuildPlans()
    {
        plans.Clear();
        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        sw.Start();
        gameObject.BroadcastMessage("PlanTurn", plans);
        sw.Stop();
        if (sw.ElapsedMilliseconds > 5f)
            Debug.LogWarning("Slow Planner!  Plans for " + name + " has candidate count=" + plans.Count + " computed in " + sw.ElapsedMilliseconds + "ms");
    }

    private void FilterPlansForPriority()
    {
        if (plans.Count <= 1)
            return;

        int topPriority = plans.Max(a => a.Priority);
        plans = new List<TurnAction>(plans.Where(a => a.Priority == topPriority));
    }

    private TurnAction ChooseRandomPlanFromList()
    {
        return ListHelper.DrawFromAtRandom(plans);
    }

}
