using System;
using Level;
using UnityEngine;

namespace UI
{
    public class LevelSelectionMenu : MonoBehaviour
    {
        [SerializeField] private Vector2Int maxGridSize = Vector2Int.one;
        private GameObject levelButtonPrefab = null;

        private void Awake()
        {
            levelButtonPrefab = Resources.Load<GameObject>("UI/Level Button Variant");
        }

        private void Start()
        {
            LevelButton instance = null;

            int rowIndex = 0;
            int columnIndex = 0;
            int i = 0;
            int count = LevelManager.Instance.Levels.Values.Count;

            RectTransform rectTransform = levelButtonPrefab.transform.GetComponent<RectTransform>();
            float rowOffset = (int)(count / maxGridSize.x) * rectTransform.rect.height * 0.75f;
            float columnOffset = -maxGridSize.x * rectTransform.rect.width * 0.75f;
            if (maxGridSize.x % 2 == 1)
                columnOffset += rectTransform.rect.width * 0.75f;

            RectTransform instanceRectTransform = null;
            Vector3 instancePosition = Vector3.zero;
            foreach (var level in LevelManager.Instance.Levels.Values)
            {
                if (i > maxGridSize.x * maxGridSize.y)
                    break;


                rowIndex = i / maxGridSize.x;
                columnIndex = i % maxGridSize.x;

                instance = Instantiate(levelButtonPrefab, transform.position, Quaternion.identity, transform).GetComponent<LevelButton>();
                instance.SetLevel(level.name);
                instanceRectTransform = instance.transform.GetComponent<RectTransform>();

                instancePosition.y = rowOffset - rowIndex * instanceRectTransform.rect.height * 1.5f;
                instancePosition.x = columnOffset + columnIndex * instanceRectTransform.rect.width * 1.5f;
                instanceRectTransform.localPosition = instancePosition;

                i++;
            }
        }
    }
}
