using GadgetCore.API;
using ScrapYard.API;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace ScrapYard
{
  [Gadget("ScrapYard", GadgetVersionSpecificity: VersionSpecificity.NONBREAKING)]
  public class ScrapYard : Gadget<ScrapYard>
  {
    public const string MOD_VERSION = "1.4.1"; // 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)");
      }

      Config.Save();
    }

    public override string GetModDescription()
    {
      return "A mod that adds a scryp yard planet. Lite Version.";
    }

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

      Texture2D textureScrapTrophy = GadgetCoreAPI.LoadTexture2D("iScrapTrophy.png");

      ItemInfo item = new ItemInfo(ItemType.GENERIC, "Scrap Trophy", "A rusty trophy.\nUsed for purchasing\nspecial items.", textureScrapTrophy);
      int itemID = ItemRegistry.Singleton.Register(item, "Scrap Trophy");
      if (itemID == -1)
        throw new System.Exception("Could not register item " + "Scrap Trophy");

      { // Shop Stand
        var asset = GadgetCoreAPI.LoadAssetBundle("scrapyardstand");
        scrapYardStand = UnityEngine.Object.Instantiate((GameObject)asset.LoadAsset("assets/resources/scrapyardstand.prefab"));
        scrapYardStand.SetActive(false);
        scrapYardStand.AddComponent<ScrapYardShopStandScript>();
        scrapYardStand.name = "scrapyardstand";

        scrapYardStand.transform.GetChild(0).GetComponent<Renderer>().material = new Material(Shader.Find("Unlit/Transparent"))
        {
          mainTexture = GadgetCoreAPI.LoadTexture2D("scrapYardStand.png")
        };

        scrapYardStand.transform.GetChild(2).GetComponent<Renderer>().material = new Material(Shader.Find("Unlit/Transparent"))
        {
          mainTexture = GadgetCoreAPI.LoadTexture2D("scrapYardStandInfo.png")
        };

        GadgetCoreAPI.AddCustomResource("prop/ScrapYard/stand", scrapYardStand);

        ItemInfo tileItem = new ItemInfo(ItemType.GENERIC, "scrapyardstand", "Degug item.", null as Texture2D).Register();
        TileInfo tile = new TileInfo(TileType.INTERACTIVE, null as Texture2D, new GameObject("scrapyardstand"), tileItem);
        int tileID = TileRegistry.Singleton.Register(tile, "scrapyardstand");
        if (tileID == -1)
          throw new System.Exception("Could not register Tile " + "scrapyardstand");
        tile.OnInteract += OnInteractStand;
      }

      ShopPlatform.Reset();

      // Setting up default shop platforms
      new ShopPlatform("Default Objects", ShopPlatformSpacingType.Near).Register("DefaultObjects");
      new ShopPlatform("Default Blocks", ShopPlatformSpacingType.Near).Register("DefaultBlocks");
      new ShopPlatform("Default Walls", ShopPlatformSpacingType.Near).Register("DefaultWalls");

      SceneManager.sceneLoaded += OnSceneLoaded;

    }

    private static GameObject scrapYardStand;

    internal static void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
      if (scene.buildIndex == 1)
      {
        InstanceTracker.GameScript.StartCoroutine(CreateStands());
        try
        {
          var storageMenu = GameObject.Find("Ship").transform.Find("SHIPPLACES").transform.Find("NPCs").transform.Find("npcFlora").localPosition = new Vector3(-134.58f, 11.72f, -0.19f);
        }
        catch (System.Exception e) { Core.logger.LogError(e.Message); }
      }
    }
    private static IEnumerator CreateStands()
    {
      while (!Network.isServer && !Network.isClient)
      {
        yield return new WaitForSeconds(0.25f);
      }
      yield return new WaitForSeconds(0.75f);
      if (Network.isServer)
      {
        try
        {
          {
            var stand = (GameObject)Network.Instantiate((GameObject)Resources.Load("prop/ScrapYard/stand"), new Vector3(-250f + 4 * -5.5f, -5.99f - 2 + 0.5f, 0.19f), Quaternion.identity, 0);
            stand.GetComponent<ScrapYardShopStandScript>().GetComponent<ScrapYardShopStandScript>().StartCallSet(ItemRegistry.GetItemIDByRegistryName("ScrapYard:Scrap Trophy"), 9999, 1, 57);
          }
          List<ShopPlatformEntry> blocks = new List<ShopPlatformEntry>();
          List<ShopPlatformEntry> objects = new List<ShopPlatformEntry>();
          foreach (var p in ShopPlatform.GetShopPlatforms())
            if (p == ShopPlatform.DefaultBlocks || p == ShopPlatform.DefaultWalls)
              foreach (var e in p.Entries)
                blocks.Add(e);
            else
              foreach (var e in p.Entries)
                objects.Add(e);
          for (int i = 0; i < System.Math.Min(objects.Count, 3); i++)
          {
            var entry = objects[i];
            var stand = (GameObject)Network.Instantiate((GameObject)Resources.Load("prop/ScrapYard/stand"), new Vector3(-250f + 4 * i, -5.99f - 2 + 0.5f, 0.19f), Quaternion.identity, 0);
            stand.GetComponent<ScrapYardShopStandScript>().StartCallSet(entry.ItemID, entry.Price, entry.Quantity, entry.CurrencyItemID);
          }
          for (int i = 0; i < System.Math.Min(blocks.Count, 5); i++)
          {
            var entry = blocks[i];
            var stand = (GameObject)Network.Instantiate((GameObject)Resources.Load("prop/ScrapYard/stand"), new Vector3(-250f + 4 * 7 + 4 * i, -5.99f + 6 + 0.5f, 0.19f), Quaternion.identity, 0);
            stand.GetComponent<ScrapYardShopStandScript>().StartCallSet(entry.ItemID, entry.Price, entry.Quantity, entry.CurrencyItemID);
          }
          if (objects.Count > 3 || blocks.Count > 5)
            Core.logger.LogWarning("There are more stands than can be added to your ship. U should use the non Lite version of Scrap Yard");
        }
        catch (System.Exception e)
        {
          Core.logger.LogError(e);
        }
      }
      yield break;
    }

    public static readonly FieldInfo canInteractField = typeof(PlayerScript).GetField("canInteract", BindingFlags.NonPublic | BindingFlags.Instance);
    public static readonly FieldInfo interactingField = typeof(PlayerScript).GetField("interacting", BindingFlags.NonPublic | BindingFlags.Instance);

    private IEnumerator OnInteractStand()
    {
      try
      {
        PlayerScript.curInteractObj.SendMessage("Request");
        canInteractField.SetValue(InstanceTracker.PlayerScript, true);
        interactingField.SetValue(InstanceTracker.PlayerScript, false);
        InstanceTracker.PlayerScript.w.SetActive(true);
      }
      catch (System.Exception e)
      {
        Core.logger.Log(e);
      }
      yield break;
    }
  }
}
