using GadgetCore.API;
using System;
using UnityEngine;

namespace CombatChipChest
{
  public class CombatChipStore
  {
    public CombatChipStore(int size, string id)
    {
      m_ChipIDs = new int[size];
      _id = id;
    }

    private string _id;

    private int[] m_ChipIDs;

    public int[] ChipIDs
    {
      get { return m_ChipIDs; }
      set { m_ChipIDs = value; }
    }

    public void Save()
    {
      for (int i = 0; i < m_ChipIDs.Length; i++)
      {
        PreviewLabs.PlayerPrefs.SetInt("customChipsStore:" + _id + ":" + i, m_ChipIDs[i]);
      }
    }

    public void Load()
    {
      for (int i = 0; i < m_ChipIDs.Length; i++)
      {
        m_ChipIDs[i] = PreviewLabs.PlayerPrefs.GetInt("customChipsStore:" + _id + ":" + i, 0);
      }
    }

    public void UpdateLatestUI()
    {
      UpdateUI(lastUsed);
    }

    private GameObject lastUsed;
    public void UpdateUI(GameObject menu)
    {
      lastUsed = menu;
      var gameScript = (GameScript)Camera.main.GetComponent("GameScript");
      try
      {
        for (int i = 0; i < menu.transform.childCount; i++)
        {
          var obj = menu.transform.GetChild(i).gameObject;
          int number;

          if (obj.name.Length > "combat_storage_slot".Length && int.TryParse(obj.name.Substring("combat_storage_slot".Length), out number))
          {
            obj.GetComponent<Renderer>().material = (Material)Resources.Load("cc/cc" + m_ChipIDs[number]);
          }
        }
      }
      catch (Exception e)
      {
        Core.logger.LogConsole(e.Message);
      }
    }

    public void UpdateText(int id)
    {
      if (lastUsed != null)
      {
        var txtChipName = lastUsed.transform.FindChild("txtTitle").gameObject.GetComponent<TextMesh>();
        txtChipName.text = GadgetCoreAPI.GetChipName(id);

        var txtDesc = lastUsed.transform.FindChild("txtDesc").gameObject.GetComponent<TextMesh>();
        txtDesc.text = GadgetCoreAPI.GetChipDesc(id);

        var gameScript = (GameScript)Camera.main.GetComponent("GameScript");
        var txtCost = lastUsed.transform.FindChild("txtCost").gameObject.GetComponent<TextMesh>();
        int chipCost =  gameScript.GetChipCost(id);

        if (chipCost == -1 && txtChipName.text != string.Empty)
          txtCost.text = "Passive";
        else if (chipCost > 0)
          txtCost.text = chipCost + " Mana";
        else
          txtCost.text = string.Empty;
      }
    }
  }
}
