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

public class CatDetector : MonoBehaviour
{
    [SerializeField] private ButtonsZoom zoom;
    [SerializeField] private GameObject Stars;
    [SerializeField] private StateTableau Tableau;
    [SerializeField] public List<GameObject> objectToActivate;

    private void OnEnable()
    {
        foreach (var obj in objectToActivate)
        {
            Image img = obj.GetComponent<Image>();
            if (img == null)
            {
                Debug.LogWarning("Le GameObject " + obj.name + " n'a pas d'Image !");
                continue;
            }
        }
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
            CheckAllImages();
    }

    void CheckAllImages()
    {

        Vector2 Pos;
        foreach (var obj in  objectToActivate)
        {
            if (IsPixelOpaque(obj.GetComponent<Image>(), Pos = GetMouseTruePos()))
            {
                obj.SetActive(true);
                if (!obj.GetComponent<PlaySound>().isSpecial)
                {
                    obj.GetComponent<Image>().color = Color.white;
                }
                else
                {
                    obj.GetComponent<Image>().color = obj.GetComponent<PlaySound>().SpecialColor;
                }
                Debug.Log("Yippie ! Pixel opaque sur " + obj.GetComponent<Image>().name);
                Instantiate(Stars, Input.mousePosition, new Quaternion(0, 0, 0, 0));
                
                Tableau.OnBoutonClick(obj);
                objectToActivate.Remove(obj);
                break;
            }
        }
    }
    [SerializeField]private Image Decor;
    private Vector2 GetMouseTruePos()
    {
        Vector2 localPoint;

        // Convertir la position de la souris écran en coordonnées locales par rapport à l'image
        RectTransformUtility.ScreenPointToLocalPointInRectangle(
            Decor.rectTransform,
            Input.mousePosition,
            null,
            out localPoint
        );

        // Récupérer les dimensions de l'image
        Rect rect = Decor.rectTransform.rect;

        // Ajuster pour que (0,0) soit le coin bas-gauche
        Vector2 truePos = new Vector2(
            localPoint.x + rect.width * Decor.rectTransform.pivot.x,
            localPoint.y + rect.height * Decor.rectTransform.pivot.y
        );

        Debug.Log("MouseLocal: " + localPoint + "\nTruePos: " + truePos);

        return truePos;
    }

    bool IsPixelOpaque(Image img, Vector2 screenPos)
    {
        RectTransform rect = img.rectTransform;

        int x = Mathf.RoundToInt(screenPos.x);
        int y = Mathf.RoundToInt(screenPos.y);

        Sprite sprite = img.sprite;
        Texture2D tex = sprite.texture;

        Color col = tex.GetPixel(x, y);

        return col.a > 0.01f;
    }


}