using UnityEngine.UI;
using UnityEngine;

namespace InterfaceOff
{
    public class ImageWindow : WindowBase
    {
        private static Vector3[] Positions =
        {
            new(-45, 25f),
            new(45f, 25f),
            new(-45, -65),
            new(45f, -65)
        };

        private int m_TilesRotatedCorrectly;
        
        public override void OnWindowInstantiation()
        {
            /* Lets the player know what to do via text */
            Components.InfoText.text = "Rotate";
            
            /* Creates the images to rotate */
            Sprite[] sprites = ImageRegistry.GetRandomSpriteSet();
            for (int i = 0; i < 4; i++)
            {
                /* Fetches/Creates needed components */
                GameObject go = Instantiate(PrefabRegistry.Instance.ImagePrefab, transform);
                RectTransform t = go.GetComponent<RectTransform>();

                t.sizeDelta = new Vector2(80, 80);
                t.localPosition = Positions[i];
                t.eulerAngles = new Vector3(0, 0, Random.Range(1, 4) * 90);
                
                Image img = go.GetComponent<Image>();
                img.material = new Material(Shader.Find("UI/Default"));
                img.sprite = sprites[i];
                
                /* Adds a function to the buttons for them to rotate */
                Button button = go.GetComponent<Button>();
                button.onClick.AddListener(() =>
                {
                    RectTransform rect = button.GetComponent<RectTransform>();
                    
                    if (!(rect.rotation.eulerAngles.z < 45 && rect.rotation.eulerAngles.z > -45))
                    {
                        Vector3 rot = rect.rotation.eulerAngles;
                        rot += new Vector3(0, 0, 90);
                        
                        rect.rotation = Quaternion.Euler(rot);
                    }

                    if (rect.rotation.eulerAngles.z < 45 && rect.rotation.eulerAngles.z > -45)
                    {
                        m_TilesRotatedCorrectly++;
                        button.interactable = false;
                    }
                });
            }
        }

        public override void OnWindowCloseButtonClicked()
        {
            if (m_TilesRotatedCorrectly == 4)
            {
                Destroy(gameObject);
            }
        }
    }
}