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

public class EggStatus : MonoBehaviour {

    public int TurnsToMature = 12;
    public float ExtraSize = 1f;

    public bool IsStolen = false;
    private GridPoint2 CENTER = new GridPoint2(5, 5);
    private int maturedTurns=0;
    private bool escaping = false;
    private Vector2 escapeDir;
    private Actor actor;
    private Vector3 origScale;

    void Start()
    {
        actor = GetComponent<Actor>();
        origScale = transform.localScale;
    }

    void StartTurn()
    {
        if (escaping)
            return;

        if (!IsStolen)
        {
            maturedTurns++;

            if (maturedTurns >= TurnsToMature)
                Mature();
        }
    }

    private void Mature()
    {
        RenderSounds.PlaySound("Birth");
        ScoreBoard.instance.BabiesHatched++;
        transform.localScale = new Vector3(1,1,1);
        transform.SendMessage("Animate", "FlyAway");        
        escaping = true;
        escapeDir = ((Vector2)(transform.position - GameMap.Cell[CENTER].transform.position)).normalized;
        if (escapeDir.magnitude == 0)
            escapeDir = new Vector2(0, 1);
        GameMap.Cell[actor.Location].RemoveActor();
    }

    void Update()
    {
        if (!escaping)
        {
            float sizeFactor = (float)maturedTurns / (float)TurnsToMature;
            transform.localScale = origScale + sizeFactor * origScale;
            return;
        }

        transform.position = transform.position + (Vector3)(escapeDir * 0.01f + Random.insideUnitCircle * 0.005f);
        if (((Vector2)(GameMap.Cell[CENTER].transform.position - transform.position)).magnitude > 4f)
            GameObject.Destroy(gameObject);
    }

}
