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

public class EggSpawner : MonoBehaviour {
    public Transform EggPrefab;
    public Transform SplatterPrefab;
    public Transform Pregnancy;
    public int Interval = 15;

    private GridPoint2 CENTER = new GridPoint2(5, 5);
    private Actor actor;
    void Start()
    {
        actor = GetComponent<Actor>();
    }

    void StartTurn()
    {
        RenderPipeline.RenderCode(() =>
        {
            float scale = (float)(TurnBasedGameLoop.instance.TurnCount % Interval) / (float)Interval;
            Pregnancy.localScale = new Vector3(scale, scale, scale) * 2f;
        });

        int useInterval = Mathf.Max(3, Interval - (int)((float)ScoreBoard.instance.BabiesHatched / 4f));

        if (TurnBasedGameLoop.instance.TurnCount % Interval == 0)
        {            
            SpawnEgg();
        }
    }

    void Update()
    {

    }

    private void SpawnEgg()
    {
        GridPoint2 pos = GetLanding();
        if (pos == GridPoint2.None)
            return;

        Transform egg = SpawnActor.SpawnPrefabAt(EggPrefab, pos);
        egg.transform.position = actor.transform.position;
        int dist = PointyHexPoint.HexNorm(actor.Location - pos);
        SmoothMovement eggFly = new SmoothMovement(egg, actor.transform.position, GameMap.Cell[pos].transform.position, 0.15f*(float)dist, 0.135f*(float)dist);
        RenderPipeline.RenderSound("EggDrop");
        RenderPipeline.RenderCode(() =>
            {
                Transform t = GameObject.Instantiate(SplatterPrefab);
                t.position = Pregnancy.position;
            }, 0.1f);
        RenderPipeline.Render(eggFly);
    }

    private GridPoint2 GetLanding()
    {
        int maxRange = (Random.Range(0, 100) < 65) ? 4 : 3;
        var valids = GameMap.instance.Grid.Points
            .Where(o =>
                {
                    int d = PointyHexPoint.HexNorm(o - actor.Location);
                    return d > 1 && d < 5;
                })
            .Where(r => 
                {
                    int d2 = PointyHexPoint.HexNorm(r - CENTER);
                    return d2 < maxRange;
                })
            .Where(p => GameMap.Available(p))
            .Where(q => !GameMap.IsEdge(q))
            .ToList();

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

        return ListHelper.DrawFromAtRandom(valids);
    }


}
