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

public class InventoryUI : MonoBehaviour, IDataPersistence {

	public GameObject inventoryUI;	
	public Transform itemsParent;
	public TextMeshProUGUI coinsCollectedText;
	public int coinsAmount;

	private bool dialogueIsActive = false;

	Inventory inventory;

	void Start ()
	{
		inventory = Inventory.instance;
		inventory.onItemChangedCallback += UpdateUI;
		GameEventsManager.instance.onCoinCollected += OnCoinCollected;
	}

	void Update ()
	{
		coinsCollectedText.text = coinsAmount.ToString();

		if(inventoryUI == null){
			inventoryUI = GameObject.Find("InventoryUI");
			return;
		}

		if(dialogueIsActive == true){
			inventoryUI.SetActive(false);
		}

		if (Input.GetButtonDown("Inventory") && dialogueIsActive == false)
		{
			Debug.Log("Pressed Inventory Key");
			inventoryUI.SetActive(!inventoryUI.activeSelf);
			UpdateUI();
		}
	}

	private void OnCoinCollected() 
    {
        coinsAmount++;
		coinsCollectedText.text = coinsAmount.ToString();
    }

	public void LoadData(GameData data){
		//Load saved coins
		foreach(KeyValuePair<string, bool> pair in data.coinsCollected) 
        {
            if (pair.Value) 
            {
                coinsAmount++;
            }
        }
	}

	public void SaveData(GameData data){
		//nothing to save here
	}

	public void UpdateUI ()
	{
		InventorySlot[] slots = GetComponentsInChildren<InventorySlot>();

		for (int i = 0; i < slots.Length; i++)
		{
			if (i < inventory.items.Count)
			{
				slots[i].AddItem(inventory.items[i]);
			} else
			{
				slots[i].ClearSlot();
			}
		}
	}


	#region dialogue-methods

	public void DialogueActive(){
		dialogueIsActive = true;
	}

	public void DialogueNotActive(){
		dialogueIsActive = false;
	}

	#endregion dialogue-methods

}