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

public class AllyUpgrade : MonoBehaviour, IPointerClickHandler
{
    [SerializeField]
    private GameObject _upgradeUI;
    [SerializeField]
    private List<UnitCard> _upgradeUnitCardList = new List<UnitCard>();
    [SerializeField]
    private List<GameObject> _upgradePrefabList = new List<GameObject>();
    private GameObject _instance = null;

    public void OnPointerClick(PointerEventData eventData)
    {
        if (eventData.button == 0)  //Left click
        {
            Debug.Log("Event clicked...");
            if (!_instance)
            {
                GameObject sceneCanvas = GameObject.Find("Canvas");
                if (sceneCanvas != null)
                {
                    Canvas canvas = sceneCanvas.GetComponent<Canvas>();
                    if (canvas == null)
                    {
                        Debug.Log("Canvas introuvable...");
                    }
                    else
                    {
                        _instance = Instantiate(_upgradeUI, Camera.main.WorldToScreenPoint(transform.position), Quaternion.identity, canvas.transform);
                        AssignUpgrades(canvas);
                    }
                }
                Debug.Log(_instance.transform.position);
                Debug.Log(Camera.main.WorldToScreenPoint(transform.position));
                
            }
            else
            {
                Destroy(_instance);
                Debug.Log("Destroyed....");
            }

        }
    }

    private void AssignUpgrades(Canvas canvas)
    {
        Debug.Log("Upgrade count: " + _instance.transform.childCount);
        // Assign upgrade Prefabs
        for (int i = 0; i < _instance.transform.childCount; i++)
        {
            GameObject upgradeEnfant = _instance.transform.GetChild(i).gameObject;
            UpgradePlacementButton button = upgradeEnfant.GetComponent<UpgradePlacementButton>();
            button.Initialize(_upgradeUnitCardList[i], _upgradePrefabList[i], gameObject, canvas);
        }
    }}
