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

public class Enemy : MonoBehaviour
{
    [SerializeField]
    GameObject moverCellPrefab;
    [SerializeField]
    GameObject eaterCellPrefab;
    [SerializeField]
    GameObject splitterCellPrefab;

    public ProxyCollider foodProxyCollider;

    int initialSizeMin = 2;
    int initialSizeMax = 5;

    float growTime = 2f;

    HeadController headController;
    Coroutine growCycle;
    List<Transform> nearbyTargets = new List<Transform>();
    Transform target;

    void Start()
    {
        var audio = GetComponent<AudioSource>();
        audio.pitch = Random.Range(0.7f, 1.3f);
        headController = GetComponent<HeadController>();
        headController.nutrition += Random.Range(initialSizeMin, initialSizeMax);
    }

    void Update()
    {
        if (growCycle == null)
        {
            growCycle = StartCoroutine(GrowCycle());
        }
        if (target == null)
        {
            FindTarget();
        }
        MoveTowardsTarget();
    }

    void FindTarget()
    {
        if (nearbyTargets.Count > 0)
        {
           target = nearbyTargets[Random.Range(0, nearbyTargets.Count)];
        } else
        {
            target = null;
        }
    }

    void MoveTowardsTarget()
    {
        Vector2 targetPosition = transform.right;
        if (target)
        {
            targetPosition = (target.position - transform.position).normalized;
        }
        headController.MoveTowards(targetPosition);
    }

    void OnEnable()
    {
        foodProxyCollider.onTriggerEnter += RegisterTarget;
        foodProxyCollider.onTriggerExit += UnregisterTarget;
    }

    void OnDisable()
    {
        foodProxyCollider.onTriggerEnter -= RegisterTarget;
        foodProxyCollider.onTriggerExit -= UnregisterTarget;
    }

    IEnumerator GrowCycle()
    {
        while (true)
        {
            if (CanGrow())
            {
                Grow();
                yield return new WaitForSeconds(Random.value * growTime);
            } else
            {
                yield return null;
            }
        }
    }

    bool CanGrow()
    {
        return headController.HasNutrition();
    }

    void Grow()
    {
        var cellPrefab = GetCellPrefab();
        GrowCell(cellPrefab);
    }

    void GrowCell(GameObject cellPrefab)
    {
        var cellCount = headController.openCells.Count;
        var selectedCell = headController.openCells[Random.Range(0, cellCount)];
        CellConnection connection = null;
        var prevCell = selectedCell;

        while (selectedCell != null)
        {
            connection = selectedCell.possibleConnections[Random.Range(0, selectedCell.possibleConnections.Count)];
            prevCell = selectedCell;
            selectedCell = connection.cell;
        }
        prevCell.GrowCell(connection, cellPrefab);
    }

    GameObject GetCellPrefab()
    {
        var random = Random.value;
        if (random < 0.2f)
        {
            return eaterCellPrefab;
        } else if (random < 0.5f)
        {
            return moverCellPrefab;
        } else
        {
            return splitterCellPrefab;
        }
    }

    void RegisterTarget(Collider2D other)
    {
        nearbyTargets.Add(other.transform);
    }

    void UnregisterTarget(Collider2D other)
    {
        nearbyTargets.Remove(other.transform);
    }

}
