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

public class TurnToFood : MonoBehaviour
{

    float targetRotation;
    float currentRotation;
    float rotationChangeVelocity;

    List<Transform> targets = new List<Transform>();

    [SerializeField] [HideInInspector] BaseCell parent;

    float lastFoodConsumeTime;
    Vector3 originalScale;
    [SerializeField] AnimationCurve foodConsumeScaleCurve;

    void OnValidate()
    {
        if (!parent)
            parent = GetComponentInParent<BaseCell>();
    }

    void OnEnable()
    {
        parent.onFoodConsumed += FoodConsumed;
        originalScale = transform.localScale;
    }

    void OnDisable()
    {
        parent.onFoodConsumed -= FoodConsumed;
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        targets.Add(other.transform);
    }

    void OnTriggerExit2D(Collider2D other)
    {
        targets.Remove(other.transform);
    }

    void FixedUpdate()
    {
        var position = transform.position;
        Transform closestTarget = null;
        float sqrDistanceToClosestTarget = float.MaxValue;

        for (int i = 0; i < targets.Count; i++)
        {
            var target = targets[i];
            if (!target)
                continue;
            
            var sqrDistanceToTarget = (position - target.position).sqrMagnitude;

            if (!closestTarget || (sqrDistanceToTarget < sqrDistanceToClosestTarget))
            {
                closestTarget = target;
                sqrDistanceToClosestTarget = sqrDistanceToTarget;
            }
        }

        targetRotation = Math2D.AngleBetweenPoints(position, closestTarget
            ? closestTarget.position
            : transform.parent.right);

        currentRotation = Mathf.SmoothDampAngle(currentRotation, targetRotation, ref rotationChangeVelocity, 1);
        transform.rotation = Math2D.AngleToRotation(currentRotation);
    }

    void Update()
    {
        var time = Time.time - lastFoodConsumeTime;
        transform.localScale = originalScale * foodConsumeScaleCurve.Evaluate(time);
    }

    void FoodConsumed()
    {
        lastFoodConsumeTime = Time.time;
    }
}
