// import {} from "./biomeGenerator";
import { } from "./eternal/tileToPlacer";
import { } from "functions/eternal/biome_craft/tick.js";
import { } from "./door";
import { } from "./trapdoor";
import { } from "./double_plant";
import { } from "./double_plant_no_loot";
import { } from "./eternal/devTools";
import { } from "./item_trigger";
import { } from "./wood";
import { } from "connect_block/stableTriggers.js";
import { } from "./AnimalUtils";
import { } from "./sounds.js";

// import {} from "./jars"; // moved this feature to glassJar.js
import { } from "./glassJar.js";
import { } from "./bouncy_murshroom.js";

import { } from "./double_slabs.js";
import { } from "./drops.js";
import { } from "./blocks";
import { } from "./crops";
import { } from "./exoskeletonArmor";
import { } from "./cookedPrimeMeat";
import { } from "./bugNet";
import { } from "./slingshot";
import { } from "./glider.js";
import { } from "./talonDagger.js";
import { } from "./eternal/modules/itemDescriptor.js";
import { } from "./panFlute.js";
import { } from "./drumset.js";

import { } from "./itemReplacer.js";

import { } from "./systems/MobSpawner.js";
import { } from "./furBoots.js";
import { } from "./systems/BiomeFogSystem.js";
import { } from "./systems/MobSpawner.js";
import { } from "./systems/BiomeFogSystem.js";
import { } from "./systems/FakeAirReplace.js";
import { } from "./systems/BiomeParticleSystem.js";

import { } from "./forms/Guidebook.js"; // change to a barrel import if adding more forms

import { } from "./debug/foods.js";

import "./components/index.js";
import "./entity/player.js";
import {
  BlockVolume,
  EntityComponentTypes,
  ItemStack,
  system,
  world,
} from "@minecraft/server";
import { blockException } from "./globalVariables.js";

world.beforeEvents.worldInitialize.subscribe((Initiate) => {
  Initiate.blockComponentRegistry.registerCustomComponent("ecbl_bc:inventory", {
    onTick: (event) => {
      const { block } = event;
      if (!block.permutation.getState("ecbl_bc:has_squirrel")) {
        const blockLoc = block.center;
        const inv = block.dimension.spawnEntity(
          "ecbl_bc:squirrel_nest_inventory",
          block.center
        );
        inv.setDynamicProperty("ecbl_bc:rel_block", blockLoc);
        start: for (let x = -1; x <= 1; x++) {
          for (let z = -1; z <= 1; z++) {
            const newBlockLoc = {
              x: blockLoc.x + x,
              y: blockLoc.y,
              z: blockLoc.z + z,
            };
            const newBlock = block.dimension.getBlock(newBlockLoc);
            if (newBlock.typeId === "minecraft:air") {
              if (block.typeId === 'ecbl_bc:squirrel_nest_empty') return;
              block.dimension
                .spawnEntity("ecbl_bc:squirrel", newBlockLoc)
                .triggerEvent("ecbl_bc:nest_spawn");

              break start;
            }
          }
        }
      }
    },
    onRandomTick: (event) => {
      const blockLoc = event.block;
      const block = event.block;
      if (event.block.permutation.getState("ecbl_bc:has_squirrel")) {
        start: for (let x = -1; x <= 1; x++) {
          for (let z = -1; z <= 1; z++) {
            const newBlockLoc = {
              x: blockLoc.x + x,
              y: blockLoc.y,
              z: blockLoc.z + z,
            };
            const newBlock = block.dimension.getBlock(newBlockLoc);
            if (newBlock.typeId === "minecraft:air") {
              block.dimension.spawnEntity("ecbl_bc:squirrel", newBlockLoc);
              event.block.setPermutation(
                event.block.permutation.withState("ecbl_bc:has_squirrel", false)
              );
              break start;
            }
          }
        }
      }
    },
    onPlayerDestroy: (event) => {
      const block = event.block;

      if (event.destroyedBlockPermutation.getState("ecbl_bc:has_squirrel")) {
        event.block.dimension.spawnEntity(
          "ecbl_bc:squirrel",
          event.block.location
        );
      }
      const invs = block.dimension.getEntities({
        maxDistance: 3,
        typeId: "ecbl_bc:squirrel_nest_inventory",
        location: block.center,
      })

      const inv = invs[0];
      const invComp = inv.getComponent(
        EntityComponentTypes.Inventory
      ).container;
      for (let slot = 0; slot < invComp.size; slot++) {
        try {
          block.dimension.spawnItem(invComp.getItem(slot), block.location);
        } catch { }
      }
      inv.remove();
      block.dimension.spawnItem(new ItemStack('ecbl_bc:squirrel_nest_empty'), block.location);
    },
  });

  Initiate.blockComponentRegistry.registerCustomComponent("ecbl_bc:ant_mound", {
    onPlayerDestroy: (event) => {
      if (event.player !== undefined)
        event.player.addTag("ecbl_mound_destroyed");
      const antAmount =
        event.destroyedBlockPermutation.getState("ecbl_bc:ant_count");
      for (let count = 0; count < antAmount; count++) {
        const entity = event.dimension.spawnEntity(
          "ecbl_bc:ant",
          event.block.location
        );
        entity.triggerEvent("ecbl_bc:angry");
      }
    },

    onTick: (event) => {
      const block = event.block;
      const blockLoc = block.location;

      if (
        !block.permutation.getState("ecbl_bc:loaded") &&
        block.typeId == "ecbl_bc:ant_mound"
      ) {
        block.setPermutation(
          block.permutation
            .withState("ecbl_bc:ant_count", Math.round(Math.random() * 1) + 1)
            .withState("ecbl_bc:loaded", true)
        );
      } else if (
        RandInt(0, 350) == 50 &&
        event.block.dimension.getEntities({
          location: event.block.location,
          type: "ecbl_bc:ant",
          maxDistance: 20,
        }).length < 7
      ) {
        const block = event.block;

        if (
          block.permutation.getState("ecbl_bc:ant_count") != undefined &&
          block.permutation.getState("ecbl_bc:ant_count") > 0
        ) {
          const blockLoc = block.location;
          start: for (let x = -1; x <= 1; x++) {
            for (let z = -1; z <= 1; z++) {
              const newBlockLoc = {
                x: blockLoc.x + x,
                y: blockLoc.y,
                z: blockLoc.z + z,
              };
              const newBlock = block.dimension.getBlock(newBlockLoc);
              if (newBlock?.typeId === "minecraft:air") {
                const entity = event.dimension.spawnEntity(
                  "ecbl_bc:ant",
                  newBlockLoc
                );

                block.setPermutation(
                  block.permutation.withState(
                    "ecbl_bc:ant_count",
                    block.permutation.getState("ecbl_bc:ant_count") - 1
                  )
                );
                break start;
              }
            }
          }
        }
      }
    },
  });
});

world.afterEvents.dataDrivenEntityTrigger.subscribe((event) => {
  if (event.eventId == "ecbl_bc:reached_home") {
    const loc = event.entity.location;
    const startLoc = { x: loc.x + 2, y: loc.y + 2, z: loc.z + 2 };
    const endLoc = { x: loc.x + -2, y: loc.y + -2, z: loc.z + -2 };
    const areaCheck = new BlockVolume(startLoc, endLoc);

    system.runJob(GetValidMound(event.entity));
  }
});

function RandInt(min, max) {
  const randAdd = Math.floor((max - min) * Math.random());
  return min + randAdd;
}

function* GetValidMound(entity) {
  let blockLoc;
  start: for (let x = -1; x <= 1; x++) {
    for (let y = -1; y <= 1; y++) {
      for (let z = -1; z <= 1; z++) {
        try {
          const block = entity.dimension.getBlock({
            x: entity.location.x + x,
            y: y + entity.location.y,
            z: z + entity.location.z,
          });

          if (block.typeId == "ecbl_bc:ant_mound") {
            block.setPermutation(
              block.permutation.withState(
                "ecbl_bc:ant_count",
                block.permutation.getState("ecbl_bc:ant_count") + 1
              )
            );
            event.entity.remove();
          }
        } catch { }
        yield;
      }
    }
  }
}
