using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class ExpPass : MonoBehaviour
{
    public Transform[] items;
    public Transform itemsParent;
    [EasyButtons.Button]
    void GetItems(){
        items = new Transform[itemsParent.childCount];
        for(int i =0; i < items.Length; i++){
            items[i] = itemsParent.GetChild(i);
        }
    }


    void Start()
    {
        DBmanager.OnStateChanged.AddListener(RefreshData);
        RefreshData();
    }

    void RefreshData(){
        
        for (int i = 0; i < items.Length; i++){
            int curIndex = 0;
            curIndex = i;
            int expPassLevel = (i +1)* 10;
            int expPassReward =(i +1) * 5;
            Transform item = items[i];
            item.GetChild(1).GetComponent<TMP_Text>().text = "Reach Level " + expPassLevel;
            Slider slider = item.GetComponentInChildren<Slider>();
            slider.GetComponentInChildren<TMP_Text>().text = DBmanager.LevelInt + " / " + expPassLevel;
            slider.minValue=0;
            slider.maxValue = expPassLevel;
            slider.value = DBmanager.LevelInt;

            item.GetComponentInChildren<Button>().interactable = expPassLevel <= DBmanager.LevelInt;
            if(expPassLevel <= DBmanager.LevelInt){
                item.GetComponentInChildren<Button>().gameObject.SetActive(!DBmanager.ExpPassCollected.Contains(expPassLevel));
            }
            item.GetComponentInChildren<Button>()?.onClick.AddListener(()=>{CollectExpPass(curIndex);});
          //  item
        }
    }

    void CollectExpPass(int i){
        Debug.Log("Collecting Exp Pass (index: " +i+ ")");

        int expPassLevel = (i +1)* 10;
        int expPassReward =(i +1) * 5;

        if(expPassLevel > DBmanager.LevelInt){
            Debug.LogError("Cannot collect, Not enough XP, This should be illegal");
            return;
        }

        DBmanager.AddCollectedExpPass(expPassLevel);
        DBmanager.SetGems(DBmanager.Gems + expPassReward);
        items[i].GetComponentInChildren<Button>().gameObject.SetActive(false);
    }
}
