﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

namespace Arugula.UI
{
    [RequireComponent(typeof(Button))]
    public class LevelSelectButton : MonoBehaviour
    {
        const string UNLOCKED = "_Unlocked";
        const string TIER = "_Tier";

        public bool Unlocked => PlayerPrefs.GetInt($"{id}{UNLOCKED}", 0) > 0;
        public int Tier => PlayerPrefs.GetInt($"{id}{TIER}", 0);

        public string id;
        public string displayName;
        public TextMeshProUGUI label;
        public GameObject lockIcon;
        public GameObject[] pips;

        private void Start()
        {
            Initialize();
        }

        [ContextMenu("Unlock")]
        public void Unlock()
        {
            PlayerPrefs.SetInt($"{id}{UNLOCKED}", 1);
            Initialize();
        }

        [ContextMenu("Lock")]
        public void Lock()
        {
            PlayerPrefs.SetInt($"{id}{UNLOCKED}", 0);
            PlayerPrefs.SetInt($"{id}{TIER}", 0);
            Initialize();
        }

        public void Initialize()
        {
            bool unlocked = Unlocked;

            int count = Tier;
            for (int i = 0; i < pips.Length; i++)
                pips[i].SetActive(unlocked && i < count);


            GetComponent<Button>().interactable = unlocked;
            lockIcon.SetActive(!unlocked);
            label.gameObject.SetActive(unlocked);

            if (label != null)
                label.text = displayName;


            var lsb = GetComponent<LoadSceneButton>();
            if (lsb != null && lsb.sceneName == "")
                GetComponent<LoadSceneButton>().sceneName = id;
        }

        public void Initialize(string id, string displayName)
        {
            this.id = id;
            this.displayName = displayName;
            Initialize();
        }

    }
}

