using GadgetCore.API;
using GadgetCore.API.ConfigMenu;
using RecipeMenuCore.API;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace RecipeMenuCore
{

  [Gadget("RecipeMenuCore", RequiredOnClients: false)]
  public class RecipeMenuCore : Gadget<RecipeMenuCore>
  {
    public const string MOD_VERSION = "1.5"; // Set this to the version of your mod.
    public const string CONFIG_VERSION = "1.0"; // Increment this whenever you change your mod's config file.

    protected override void LoadConfig()
    {
      Config.Load();
      string fileVersion = Config.ReadString("ConfigVersion", CONFIG_VERSION, comments: "The Config Version (not to be confused with mod version)");
      if (fileVersion != CONFIG_VERSION)
      {
        Config.Reset();
        Config.WriteString("ConfigVersion", CONFIG_VERSION, comments: "The Config Version (not to be confused with mod version)");
      }

      Core.settingUseDialog = Config.ReadBool("UseDialog", true, comments: new string[] { "Should an item dialog be shown in recipe menus?" });

      Config.Save();
    }

    public override string GetModDescription()
    {
      return "A utility mod providing a recipe menu API.";
    }

    protected override void Initialize()
    {
      Logger.Log("Recipe Menu Core v" + Info.Mod.Version);
      Core.logger = Logger;

      Core.pageGearForgeInfoList = new List<RecipePage>();
      Core.pageAlchemyStationInfoList = new List<RecipePage>();
      Core.pageUltimateForgeInfoList = new List<RecipePage>();
      SceneManager.sceneLoaded += OnSceneLoaded;
    }

    internal static void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
      if (scene.buildIndex == 1)
      {
        var menuRecipeElement = GameObject.Find("Main Camera").transform.Find("menuRecipe");
        var locksElement = menuRecipeElement.Find("ultLocks").gameObject;
        var hoverElements = Object.Instantiate(locksElement, menuRecipeElement.transform);
        hoverElements.name = "hoverElements";
        for (int i = 0; i < 12 * 3; i++)
        {
          var element = hoverElements.transform.GetChild(i).gameObject;
          Component.DestroyImmediate(element.GetComponent<Renderer>());
          var collider = element.AddComponent<BoxCollider>();
          collider.size = new Vector3(14f / 32f * 2, (18f + 1) / 32f * 2, 1);
          collider.isTrigger = true;
          element.tag = "recipe";
          element.layer = 16;
          element.name = "" + (i + 12);
        }
        var buttonsElement = menuRecipeElement.Find("buttons").gameObject;
        for (int i = 0; i < 12; i++)
        {
          var element = buttonsElement.transform.GetChild(i).gameObject;
          var collider = element.GetComponent<BoxCollider>();
          collider.size = new Vector3(collider.size.x, 0.6f, collider.size.z);
        }
      }
    }
  }
}
