import { TimeOfDay, system, world, ItemStack, StructureAnimationMode, StructureRotation, StructureSaveMode } from "@minecraft/server";
import { checkBelowEntityDespawn, getStringBefore, checkLocation, getEntityRotation, getLocationbyFacingBlock, stringBetween, getGamemode, getElementPosition, getElementPositionArrayWithObjects } from "./helpers";
import { cameraCutscene } from "../events/camera";
import { ActionFormData } from "@minecraft/server-ui";

const itemEffectsMapping = {
  "hb_cb:carrot_soup": [],

  "hb_cb:glow_berry_soup": [{ effect: "night_vision", duration: 1200, amplifier: 0 }],

  "hb_cb:parrot_soup": [],

  "hb_cb:pumpkin_soup": [],

  "hb_cb:sweet_berry_soup": [],

  "hb_cb:beef_stew": [{ effect: "strength", duration: 600, amplifier: 0 }],

  "hb_cb:golden_stew": [
    { effect: "absorption", duration: 3600, amplifier: 0 },
    { effect: "resistance", duration: 9000, amplifier: 0 },
    { effect: "fire_resistance", duration: 9000, amplifier: 0 },
    { effect: "regeneration", duration: 1200, amplifier: 2 },
  ],

  "hb_cb:nether_stew": [{ effect: "fire_resistance", duration: 1200, amplifier: 0 }],

  "hb_cb:rotten_stew": [
    { effect: "nausea", duration: 200, amplifier: 0 },
    { effect: "hunger", duration: 600, amplifier: 0 },
  ],

  "hb_cb:tropical_stew": [{ effect: "water_breathing", duration: 1200, amplifier: 0 }],
};

export class foodHandler {
  static initialized = false;
  constructor() {
    this.initialize();
  }

  initialize() {
    if (!foodHandler.initialized) {
      foodHandler.initialized = true;
      this.processSubscriptions();
    } else {
    }
  }
  processSubscriptions() {
    let curTick = 0;
    const INIT_TIME = 0;

    world.afterEvents.itemCompleteUse.subscribe((event) => {
      const player = event.source;
      const item = event.itemStack;
      const typeId = player.typeId;
      if (typeId !== "minecraft:player") {
        return;
      }
      if (item == undefined) {
        return;
      }
      if (item.typeId.includes("hb_cb:") && (item.typeId.includes("soup") || item.typeId.includes("stew"))) {
        this.checkHeldItemAndApplyEffects(player, item);
      } else return;
    });
  }

  checkHeldItemAndApplyEffects(player, item) {
    const itemId = item.typeId; // Get the item ID
    const effects = itemEffectsMapping[itemId] || []; // Get effects for the item, default to none
    let gamemodeCreative = getGamemode(player, 1);
    if (!gamemodeCreative) player.runCommand("/give @s bowl");
    if (effects.length === 0) return;
    // Apply effects
    effects.forEach((effect) => {
      if (!effect.effect || typeof effect.duration !== "number" || typeof effect.amplifier !== "number") return;
      player.addEffect(effect.effect, effect.duration, { amplifier: effect.amplifier, showParticles: true });
    });
  }
}
