import { beforeEvents, end, nether, overworld } from "./Eternal/Constants";
import { display, fetchAllEntities, runInterval, runTimeout } from "./Eternal/Utils";

const crops = ["eternal:pikomato_spawn_egg", "eternal:leleonion_spawn_egg", "eternal:marshcorn_spawn_egg"];
const cropEntityIds = crops.map((crop) => crop.replace("_spawn_egg", ""));

let delay = 0;

beforeEvents.itemUseOn.subscribe((e) => {
  if (delay > 0) {
    e.cancel = true;
    return;
  }

  runTimeout(() => {
    delay = 0;
  }, 2);

  delay++;

  const { itemStack, block, source, blockFace } = e;
  const isCrop = crops.includes(itemStack.typeId);

  if (!isCrop) return;

  e.cancel = true;
  if (block.typeId !== "minecraft:farmland" || blockFace !== "Up") return;

  const entityId = itemStack.typeId.replace("_spawn_egg", "");

  const loc = block.bottomCenter();
  loc.y++;
  runTimeout(() => {
    const blockingEntity = block.dimension.getEntities({
      families: ["crops"],
      location: block.location,
      volume: { x: 0, y: 1, z: 0 },
    })[0];
    const blockingBlock = block.offset({ x: 0, y: 1, z: 0 }).typeId != "minecraft:air";

    if (blockingEntity || blockingBlock) return;

    block.dimension.spawnEntity(entityId, loc);
    source.commandRunAsync(`clear @s ${itemStack.typeId} -1 1`);
  });
});

function fetchEntitiesFromAllDimensions(entityIds) {
  const entities = [];
  for (const entityId of entityIds) {
    entities.push(...overworld.getEntities({ type: entityId }));
    entities.push(...nether.getEntities({ type: entityId }));
    entities.push(...end.getEntities({ type: entityId }));
  }
  return entities;
}

runInterval(() => {
  const entities = fetchEntitiesFromAllDimensions(cropEntityIds);

  for (const entity of entities) {
    entity.commandRun(`execute unless block ~~-1~ farmland run event entity @s start_remove`);
  }
}, 1);
