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

public class DropEggWhenHit : MonoBehaviour 
{

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

    void Died()
    {
        if(actor.IsCarryingEgg)
        {
            DropEggAt(actor.Location);
        }
    }

    void Slammed()
    {
        if (actor.IsCarryingEgg)
        {
            GridPoint2 drop = GetFreeDropSpot();            
            if (drop == GridPoint2.None)
                return;

            DropEggAt(drop);
        }
    }

    private void DropEggAt(GridPoint2 drop)
    {
        Actor egg = GetEgg();
        GameMap.Cell[drop].SetActor(egg);
        egg.Location = drop;
        egg.transform.parent = null;
        egg.GetComponent<EggStatus>().IsStolen = false;
        egg.SendMessage("Animate", "Idle");
        actor.IsCarryingEgg = false;

        SmoothMovement plop = new SmoothMovement(egg.transform, egg.transform.position, GameMap.Cell[drop].transform.position, 0.1f);
        RenderPipeline.Render(plop);
    }

    private GridPoint2 GetFreeDropSpot()
    {
        var valids = PointyHexPoint.GetOrthogonalNeighbors(actor.Location)
            .Where(p => GameMap.Available(p));

        if (valids.Count() == 0)
            return GridPoint2.None;
        else
            return ListHelper.DrawFromAtRandom(valids.ToList());
    }

    private Actor GetEgg()
    {
        return transform.FindChild("Egg(Clone)").GetComponent<Actor>();
    }

}
