using GadgetCore.API;
using GadgetCore.Util;
using RecipeMenuCore.API;
using Ships.API;
using System.Collections;
using System.Reflection;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace Ships
{
  [Gadget("Ships", LoadAfter: new string[] { "RecipeMenuCore" }, Dependencies: new string[] { "RecipeMenuCore" })]
  public class Ships : Gadget<Ships>
  {
    public const string MOD_VERSION = "1.0"; // 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 ships that can be reaided.";
    }

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

      Texture2D texturePlanetIcon = GadgetCoreAPI.LoadTexture2D("planetShip.png");
      Texture2D texturePlanetPrevIcon = GadgetCoreAPI.LoadTexture2D("planetShipsPrev.png");
      Texture2D texturePortalSign = GadgetCoreAPI.LoadTexture2D("signShip.png");

      Texture2D textureBG = GadgetCoreAPI.LoadTexture2D("bgShips.png");
      Texture2D textureBGExtension = GadgetCoreAPI.LoadTexture2D("bgShipsExtension.png");
      Texture2D textureBGTop = GadgetCoreAPI.LoadTexture2D("bgShipsTop.png");

      Texture2D textureParalex = GadgetCoreAPI.LoadTexture2D("parallax.png");
      Texture2D textureParalex0 = GadgetCoreAPI.LoadTexture2D("bShipsbg0.png");
      Texture2D textureParalex1 = GadgetCoreAPI.LoadTexture2D("bShipsbg1.png");
      Texture2D textureParalex2 = GadgetCoreAPI.LoadTexture2D("bShipsbg2.png");
      Texture2D textureParalex3 = GadgetCoreAPI.LoadTexture2D("bShipsbg3.png");

      Texture2D textureEntrance = GadgetCoreAPI.LoadTexture2D("entranceShips.png");
      Texture2D textureSmallSide = GadgetCoreAPI.LoadTexture2D("sideSmallShips.png");
      Texture2D textureBigSide = GadgetCoreAPI.LoadTexture2D("sideBigShips.png");

      Texture2D textureMid0 = GadgetCoreAPI.LoadTexture2D("midShipsChunk0.png");
      Texture2D textureMid1 = GadgetCoreAPI.LoadTexture2D("midShipsChunk1.png");

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

      AudioClip audioShip = GadgetCoreAPI.LoadAudioClip("01_space.ogg");

      Core.shipPlanet = new PlanetInfo(PlanetType.SPECIAL, "Ship", new GadgetCore.Util.Tuple<int, int>[] { new GadgetCore.Util.Tuple<int, int>(1, 100) }, audioShip);
      var scrapYardPlanet = Core.shipPlanet;
      scrapYardPlanet.SetPortalInfo(texturePortalSign, texturePlanetPrevIcon, texturePlanetIcon);
      scrapYardPlanet.SetBackgroundInfo(textureParalex, textureParalex0, textureParalex1, textureParalex2, textureParalex3);
      scrapYardPlanet.SetTerrainInfo(textureEntrance, textureBG, textureMid0, textureMid1, textureBigSide, textureSmallSide);

      scrapYardPlanet.OnGenerateWorld += ShipGenerator.Genarate;
      scrapYardPlanet.OnGenerateTown += ShipGenerator.Genarate;
      scrapYardPlanet.Register("Ship");

      scrapYardPlanet.PortalUses = -1;

      Texture2D textureShipAEntranceFG = GadgetCoreAPI.LoadTexture2D("shipAEntranceFG.png");
      Texture2D textureShipAEntranceBG = GadgetCoreAPI.LoadTexture2D("shipAEntranceBG.png");
      CreateShipPart("ShipAEntrance", textureShipAEntranceFG, textureShipAEntranceBG, new int[][] {
        new int[] { 11, 5, 5, 1}
      , new int[] { 11, 5, 1, 6}
      , new int[] { 11, 10, 5, 1}
      }, new int[][] { }, 16, 16);

      Texture2D textureShipAMainFG = GadgetCoreAPI.LoadTexture2D("shipAMainFG.png");
      Texture2D textureShipAMainBG = GadgetCoreAPI.LoadTexture2D("shipAMainBG.png");
      CreateShipPart("ShipAMain", textureShipAMainFG, textureShipAMainBG, new int[][] {
        new int[] { 0, 0, 32, 1}
      , new int[] { 0, 15, 32, 1}
      , new int[] { 0, 0, 1, 6}
      , new int[] { 31, 0, 1, 6}
      , new int[] { 0, 10, 1, 6}
      , new int[] { 31, 10, 1, 6}
      , new int[] { 3, 5, 4, 1}
      , new int[] { 9, 5, 4, 1}
      , new int[] { 19, 5, 4, 1}
      , new int[] { 25, 5, 4, 1}
      , new int[] { 3, 10, 4, 1}
      , new int[] { 9, 10, 4, 1}
      , new int[] { 19, 10, 4, 1}
      , new int[] { 25, 10, 4, 1}
      }, new int[][] {
        new int[] { 3, 7, 0 }
      , new int[] { 6, 7, 1 }
      , new int[] { 25, 7, 1 }
      , new int[] { 28, 7, 0 }
      });

      Texture2D textureShipAExitFG = GadgetCoreAPI.LoadTexture2D("shipAExitFG.png");
      Texture2D textureShipAExitBG = GadgetCoreAPI.LoadTexture2D("shipAExitBG.png");
      CreateShipPart("ShipAExit", textureShipAExitFG, textureShipAExitBG, new int[][] {
        new int[] { 0, 5, 10, 1}
      , new int[] { 0, 10, 13, 1}
      , new int[] { 10, 6, 2, 1}
      , new int[] { 12, 7, 1, 4}
      }, new int[][] {
        new int[] { 5, 7, 0 }
      }, 16, 16);

      CreateObject("BrokenTeleporter", GadgetCoreAPI.LoadTexture2D("brokenTeleporter.png"), true);

      CreateBrakableObject("BrokenPirate1", GadgetCoreAPI.LoadTexture2D("brokenPirate1.png"), true);
      CreateBrakableObject("BrokenPirate2", GadgetCoreAPI.LoadTexture2D("brokenPirate2.png"), true);
      CreateBrakableObject("BrokenPirate3", GadgetCoreAPI.LoadTexture2D("brokenPirate3.png"), true);
      CreateBrakableObject("BrokenPirate4", GadgetCoreAPI.LoadTexture2D("brokenPirate4.png"), true);
      CreateBrakableObject("BrokenPirate5", GadgetCoreAPI.LoadTexture2D("brokenPirate5.png"), true);
      CreateBrakableObject("BrokenPirate6", GadgetCoreAPI.LoadTexture2D("brokenPirate6.png"), true);

      CreateBrakableObject("BrokenCrates1", GadgetCoreAPI.LoadTexture2D("brokenCrates1.png"));
      CreateBrakableObject("BrokenCrates2", GadgetCoreAPI.LoadTexture2D("brokenCrates2.png"));
      CreateBrakableObject("BrokenCrates3", GadgetCoreAPI.LoadTexture2D("brokenCrates3.png"));
      CreateBrakableObject("BrokenCrates4", GadgetCoreAPI.LoadTexture2D("brokenCrates4.png"));
      CreateBrakableObject("BrokenItemMod", GadgetCoreAPI.LoadTexture2D("brokenItemMod.png"));
      CreateBrakableObject("BrokenChest", GadgetCoreAPI.LoadTexture2D("brokenChest.png"));

      CreateSliverEnemy("BrokenSliver", GadgetCoreAPI.LoadTexture2D("brokenSliverHead.png"), GadgetCoreAPI.LoadTexture2D("brokenSliverBody.png"), GadgetCoreAPI.LoadTexture2D("brokenSliverTail.png"));

      ItemInfo itemInfo = new ItemInfo(ItemType.GENERIC, "port5", "", null as Texture2D).Register("port5");
      TileInfo tile = new TileInfo(TileType.INTERACTIVE, null as Texture2D, new GameObject("port5"), itemInfo).Register("port5");

      CreateOldChest("OldChest", GadgetCoreAPI.LoadTexture2D("oldChest.png"));


      Core.itemOldTex = new ItemInfo(ItemType.GENERIC, "Old Tec", "Some peace of old\ntechnology", GadgetCoreAPI.LoadTexture2D("iOldTec.png"));
      ItemRegistry.Singleton.Register(Core.itemOldTex, "oldtec");


      Core.itemOldTexShield = new ItemInfo(ItemType.OFFHAND, "Old Tec Shield", "", GadgetCoreAPI.LoadTexture2D("iOldTecShield.png"), Stats: new EquipStats(1, 1, 1, 1, 3, 0),
         HeldTex: GadgetCoreAPI.LoadTexture2D("iOldTecShield.png"));
      ItemRegistry.Singleton.Register(Core.itemOldTexShield, "oldtecshield");

      Core.itemOldTexHelmet = new ItemInfo(ItemType.HELMET, "Old Tec Helmet", "", GadgetCoreAPI.LoadTexture2D("iOldTecHelmet.png"), Stats: new EquipStats(1, 1, 1, 1, 3, 0),
         HeadTex: GadgetCoreAPI.LoadTexture2D("hOldTecHelmet.png"));
      ItemRegistry.Singleton.Register(Core.itemOldTexHelmet, "oldtechelmet");

      Core.itemOldTexArmor = new ItemInfo(ItemType.ARMOR, "Old Tec Armor", "", GadgetCoreAPI.LoadTexture2D("iOldTecArmor.png"), Stats: new EquipStats(1, 1, 1, 1, 3, 0),
         BodyTex: GadgetCoreAPI.LoadTexture2D("bOldTecArmor.png"), ArmTex: GadgetCoreAPI.LoadTexture2D("aOldTecArmor.png"));
      ItemRegistry.Singleton.Register(Core.itemOldTexArmor, "oldtecarmor");

      Core.itemOldTexDroid = new ItemInfo(ItemType.DROID, "Old Tec Droid", "", GadgetCoreAPI.LoadTexture2D("iOldTecDroid.png"), Stats: new EquipStats(1, 1, 1, 1, 3, 0),
         BodyTex: GadgetCoreAPI.LoadTexture2D("dOldTecDroidBase.png"), HeadTex: GadgetCoreAPI.LoadTexture2D("dOldTecDroidTop.png"));
      ItemRegistry.Singleton.Register(Core.itemOldTexDroid, "oldtecdroid");

      var recipePage = new RecipePage(RecipePageType.UniversalCrafter, "Old Tec", GadgetCoreAPI.LoadTexture2D("recipesOldTec")).Register();
      recipePage.AddRecipePageEntry(new RecipePageEntry(Core.itemOldTex.GetID(), Core.itemOldTex.GetID(), 133, Core.itemOldTexShield.GetID(), allwaysShowInput: true));
      recipePage.AddRecipePageEntry(new RecipePageEntry(Core.itemOldTex.GetID(), Core.itemOldTex.GetID(), 123, Core.itemOldTexHelmet.GetID(), allwaysShowInput: true));
      recipePage.AddRecipePageEntry(new RecipePageEntry(Core.itemOldTex.GetID(), Core.itemOldTex.GetID(), 103, Core.itemOldTexArmor.GetID(), allwaysShowInput: true));
      recipePage.AddRecipePageEntry(new RecipePageEntry(Core.itemOldTex.GetID(), Core.itemOldTex.GetID(), 113, Core.itemOldTexDroid.GetID(), allwaysShowInput: true));

      var universalCrafter = ((CraftMenuInfo)MenuRegistry.Singleton["Gadget Core:Crafter Menu"]);
      universalCrafter.AddCraftPerformer(CraftMenuInfo.CreateSimpleCraftPerformer(
        Tuple.Create(new int[] { Core.itemOldTex.GetID(), Core.itemOldTex.GetID(), 133 }, new Item(Core.itemOldTexShield.GetID(), 1, 0, 0, 0, new int[3], new int[3]), 0)));
      universalCrafter.AddCraftPerformer(CraftMenuInfo.CreateSimpleCraftPerformer(
       Tuple.Create(new int[] { Core.itemOldTex.GetID(), Core.itemOldTex.GetID(), 123 }, new Item(Core.itemOldTexHelmet.GetID(), 1, 0, 0, 0, new int[3], new int[3]), 0)));
      universalCrafter.AddCraftPerformer(CraftMenuInfo.CreateSimpleCraftPerformer(
        Tuple.Create(new int[] { Core.itemOldTex.GetID(), Core.itemOldTex.GetID(), 103 }, new Item(Core.itemOldTexArmor.GetID(), 1, 0, 0, 0, new int[3], new int[3]), 0)));
      universalCrafter.AddCraftPerformer(CraftMenuInfo.CreateSimpleCraftPerformer(
        Tuple.Create(new int[] { Core.itemOldTex.GetID(), Core.itemOldTex.GetID(), 113 }, new Item(Core.itemOldTexDroid.GetID(), 1, 0, 0, 0, new int[3], new int[3]), 0)));

      tile.OnInteract += Tile_OnInteract;
    }

    private IEnumerator Tile_OnInteract()
    {
      InstanceTracker.PlayerScript.Portal(5);
      yield break;
    }

    private void CreateShipPart(string name, Texture texture, Texture textureBG, int[][] collisions, int[][] lamp, int tileW = 32, int tileH = 16)
    {
      var gameObject = Object.Instantiate((GameObject)Resources.Load("z/chunk"));
      gameObject.transform.localScale = new Vector3(tileW * 2, tileH * 2, 1);

      var rendererBody = gameObject.GetComponentInChildren<Renderer>();
      rendererBody.material = new Material(Shader.Find("Transparent/Diffuse"))
      {
        mainTexture = texture
      };

      for (int i = 0; i < 6; i++)
        GameObject.DestroyImmediate(gameObject.transform.GetChild(0).gameObject);
      for (int i = 0; i < 16; i++)
        GameObject.DestroyImmediate(gameObject.transform.GetChild(1).gameObject);

      for (int i = 0; i < 7; i++)
        GameObject.DestroyImmediate(gameObject.transform.GetChild(0).GetChild(0).gameObject);

      Component.DestroyImmediate(gameObject.GetComponent<Chunk>());

      var bgRenderObject = GameObject.Instantiate(gameObject);
      for (int i = 0; i < bgRenderObject.transform.childCount; i++)
        GameObject.DestroyImmediate(bgRenderObject.transform.GetChild(0).gameObject);

      bgRenderObject.transform.SetParent(gameObject.transform);
      bgRenderObject.transform.localScale = new Vector3(1, 1, 1);
      bgRenderObject.transform.localPosition = new Vector3(0, 0, -0.3f);
      var rendererBG = bgRenderObject.GetComponent<Renderer>();
      rendererBG.material = new Material(Shader.Find("Transparent/Diffuse"))
      {
        mainTexture = textureBG
      };

      GameObject root = gameObject.transform.GetChild(0).gameObject;
      GameObject inst = root.transform.GetChild(0).gameObject;

      for (int i = 0; i < collisions.Length; i++)
      {
        GameObject entry = GameObject.Instantiate(inst);

        entry.transform.SetParent(root.transform);

        int[] coll = collisions[i];

        float w = coll[2] * (2.0f / tileW);
        float h = coll[3] * (2.0f / tileH);

        float x = coll[0] * (2.0f / tileW) + w / 2;
        float y = coll[1] * (2.0f / tileH) + h / 2;

        entry.transform.localScale = new Vector3(w, h, 1);
        entry.transform.localPosition = new Vector3(x - 1, y - 1, 0);
      }

      for (int i = 0; i < lamp.Length; i++)
      {
        int[] coll = lamp[i];

        float w = (2.0f / tileW);
        float h = (2.0f / tileH);
        int type = coll[2];

        float x = coll[0] * (2.0f / tileW) + w / 2;
        float y = coll[1] * (2.0f / tileH) + h / 2;

        GameObject entry = null;

        if (type == 0)
          entry = Object.Instantiate<GameObject>((GameObject)Resources.Load("prop/" + 2401));
        if (type == 1)
          entry = Object.Instantiate<GameObject>((GameObject)Resources.Load("prop/" + 2402));

        entry.transform.SetParent(root.transform);

        entry.transform.localScale = new Vector3(w / 4, h / 4, 1);
        entry.transform.localPosition = new Vector3(x - 1, y - 1, -1);
      }

      GameObject.DestroyImmediate(gameObject.transform.GetChild(0).GetChild(0).gameObject);

      GadgetCoreAPI.AddCustomResource("z/Ships/" + name, gameObject);
    }

    private void CreateObject(string name, Texture2D texture, bool large = false)
    {
      GameObject gameObject = Object.Instantiate<GameObject>((GameObject)Resources.Load("prop/2501"));
      Renderer renderer = gameObject.GetComponentInChildren<Renderer>();
      renderer.material = new Material(Shader.Find("Unlit/Transparent"))
      {
        mainTexture = texture
      };
      if (large)
        gameObject.transform.localScale = new Vector3(gameObject.transform.localScale.x * 2, gameObject.transform.localScale.y * 2, 1);
      GadgetCoreAPI.AddCustomResource("obj/Ships/" + name, gameObject);
    }

    private void CreateBrakableObject(string name, Texture2D texture, bool large = false, ObjectType type = ObjectType.ORE)
    {
      var i = new ObjectInfo(type, new Item(57, 1, 0, 0, 0, new int[3], new int[3]), 16, texture).Register(name);
      if (large)
      {
        var t = i.Object.transform.GetChild(0);
        t.localScale = new Vector3(4, 4, 1);
      }
      GadgetCoreAPI.AddCustomResource("obj/Ships/" + name, i.Object);
      Core.spawnObjects.Add(i.GetID());
    }

    private void CreateSliverEnemy(string name, Texture2D textureHead, Texture2D textureBody, Texture2D textureTail)
    {
      GameObject gameObject = Object.Instantiate<GameObject>((GameObject)Resources.Load("e/sliver"));
      Renderer rendererHead = gameObject.transform.GetChild(4).GetChild(0).GetChild(0).GetComponentInChildren<Renderer>();
      rendererHead.material = new Material(Shader.Find("Unlit/Transparent"))
      {
        mainTexture = textureHead
      };
      Renderer rendererBody = gameObject.transform.GetChild(4).GetChild(0).GetChild(1).GetComponentInChildren<Renderer>();
      rendererBody.material = new Material(Shader.Find("Unlit/Transparent"))
      {
        mainTexture = textureBody
      };
      Renderer rendererTail = gameObject.transform.GetChild(4).GetChild(0).GetChild(2).GetComponentInChildren<Renderer>();
      rendererTail.material = new Material(Shader.Find("Unlit/Transparent"))
      {
        mainTexture = textureTail
      };
      GadgetCoreAPI.AddCustomResource("e/Ships/" + name, gameObject);
    }

    private void CreateOldChest(string name, Texture texture)
    {
      GameObject gameObject = Object.Instantiate<GameObject>((GameObject)Resources.Load("obj/chest"));
      Renderer renderer = gameObject.transform.GetChild(0).gameObject.GetComponentInChildren<Renderer>();
      renderer.material = new Material(Shader.Find("Unlit/Transparent"))
      {
        mainTexture = texture
      };
      Component.DestroyImmediate(gameObject.GetComponent<ChestScript>());
      gameObject.AddComponent<OldChestScript>();
      GadgetCoreAPI.AddCustomResource("obj/Ships/" + name, gameObject);
    }
  }
}
