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

public class GoalApproachEgg : MonoBehaviour 
{

    private Actor actor;
    void Start()
    {
        actor = GetComponent<Actor>();
    }

    public void PlanTurn(List<TurnAction> actions)
    {
        if (actor.IsCarryingEgg)
            return;

        GridPoint2 egg = NearestEgg();
        if (egg != GridPoint2.None)
        {
            Approach(actions, egg);
        }            
    }

    private void Approach(List<TurnAction> actions, GridPoint2 egg)
    {
        GridPoint2 dest = PointyHexPoint.GetOrthogonalNeighbors(actor.Location)
            .Where(o => GameMap.Available(o))
            .OrderBy(p => PointyHexPoint.HexNorm(p - egg))
            .FirstOrDefault();

        actions.Add(new ActionMove(actor, actor.Location, dest));
    }

    private GridPoint2 NearestEgg()
    {
        var eggs = GameMap.instance.Grid.Points
            .Where(p => GameMap.Cell[p].HasActor())
            .Where(q => GameMap.Cell[q].Actor.name == "Egg(Clone)");

        if (eggs.Count() == 0)
            return GridPoint2.None;

        return eggs.OrderBy(r => PointyHexPoint.HexNorm(r - actor.Location))
            .FirstOrDefault();
    }
}
