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

public class MouseArrowsController : MonoBehaviour
{
    public GameController   gameController;
    public ColourManager    colourManager;
    public int              maxHoles;
    public Texture2D        arrowTexture;
    
    private const float         radius = 5.0f;
    private GameObject[]        arrowObjects;
    private SpriteRenderer[]    arrowSpriteRenderers;

    // Start is called before the first frame update
    private void Start()
    {
        // Create the arrows
        arrowObjects = new GameObject[maxHoles];
        arrowSpriteRenderers = new SpriteRenderer[maxHoles];

        for (int i = 0; i < arrowObjects.Length; ++i)
        {
            arrowObjects[i] = new GameObject("Arrow " + i);
            arrowObjects[i].transform.parent = transform;
            arrowObjects[i].transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);

            arrowSpriteRenderers[i] = arrowObjects[i].AddComponent<SpriteRenderer>();
            arrowSpriteRenderers[i].sprite = Sprite.Create(arrowTexture, new Rect(0, 0, arrowTexture.width, arrowTexture.height), new Vector2(0.5f, 0.5f));

            arrowObjects[i].SetActive(false);
        }
    }

    // Update is called once per frame
    private void Update()
    {
        for (int i = 0; i < gameController.activeHoles.Count; ++i)
        {
            // Get the direction of the player to the hole
            Vector3 dir = gameController.activeHoles[i].transform.position - transform.position;
            dir.z = 0;
            dir.Normalize();

            // Set the position of the arrow
            arrowObjects[i].transform.position = transform.position + dir * radius;

            // Get the angle of the direction
            float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;

            // Set the rotation of the arrow
            arrowObjects[i].transform.rotation = Quaternion.Euler(0, 0, angle);

            // Set the color of the arrow to the hole color
            arrowSpriteRenderers[i].color = gameController.activeHoles[i].GetComponent<SpriteRenderer>().color;

            // Set the alpha of the arrow based on the visibility of the hole
            if (gameController.activeHoles[i].GetComponent<SpriteRenderer>().isVisible)
            {
                arrowSpriteRenderers[i].color = new Color(arrowSpriteRenderers[i].color.r, arrowSpriteRenderers[i].color.g, arrowSpriteRenderers[i].color.b, 0);
            }
            else
            {
                arrowSpriteRenderers[i].color = new Color(arrowSpriteRenderers[i].color.r, arrowSpriteRenderers[i].color.g, arrowSpriteRenderers[i].color.b, 255);
            }

            // Enable the arrow 
            arrowObjects[i].SetActive(true);
        }

        for (int i = gameController.activeHoles.Count; i < maxHoles; ++i)
        {
            arrowObjects[i].SetActive(false);
        }
    }
}
