using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Sirenix.OdinInspector;
using NUnit.Framework.Internal;
using FIMSpace.FEyes;
using Unity.VisualScripting;

public class GooglyEyeAdder : MonoBehaviour
{
    public GameObject eyePrefab;
    public int eyeCountMin = 1;
    public int eyeCountMax = 5;

    public float scaleMin = 0.25f;
    public float scaleMax = 2.0f;

    private float randomSacle => Random.Range(scaleMin, scaleMax);

    public List<GameObject> eyes = new List<GameObject>();

    [Button]
    public void AddEyes(MeshFilter meshFilter)
    {
        if(meshFilter == null) {
            return;
        }
        DestroyEyes();
        eyes = new List<GameObject>();
        int eyesToAdd = Random.Range(eyeCountMin, eyeCountMax);
        for(int i = 0; i < eyesToAdd; i += 1) {
            SpawnEye(RandomVertex(meshFilter), meshFilter.transform);
        }
    }

    void DestroyEyes()
    {
        foreach(GameObject eye in eyes) {
            if (eye == null) {
                continue;
            }
            Destroy(eye);
        }
        eyes.Clear();
    }


    void SpawnEye(Vector3 position, Transform parent)
    {
        if (eyePrefab == null) {
            Debug.LogError($"No eye prefab set in gameobject {gameObject.name}");
            return;
        }
        GameObject spawnedEye = Instantiate(eyePrefab, parent);
        spawnedEye.transform.localPosition = position;
        float scale = randomSacle;
        spawnedEye.transform.localScale = new Vector3(scale, scale, scale);
        eyes.Add(spawnedEye);
    }

    Vector3 RandomVertex(MeshFilter meshFilter)
    {
        Mesh mesh = meshFilter.sharedMesh;
        Vector3[] vertices = mesh.vertices;
        int index = Random.Range(0, vertices.Length - 1);
        return vertices[index];
    }

    public void LookAt(Transform target)
    {
        foreach (GameObject eye in eyes) {
            FEyesAnimator eyesAnimator = eye.GetComponent<FEyesAnimator>();
            eyesAnimator.SetEyesTarget(target);
        }
    }
}
