import { world, system, Dimension } from "@minecraft/server"
import { ActionFormData } from "@minecraft/server-ui"


let ui
let customUi
let scarUi
let mp7Ui;

world.afterEvents.worldLoad.subscribe(() => {
  ui = new ActionFormData()
    .title("Form")
    .body("")
    .button("Balls")


  customUi = new ActionFormData()
    .title("Attachments")
    .body("")
    .button("MP 7")
    .button("Scar H")
  scarUi = new ActionFormData()
    .title("SCAR H Attachments")
    .body("")
    .button("Remove Attachment")
    .button("Add Suppressor")
    .button("Add Acog")
    .button("Add Reddot")
    .button("Add Foregrip")
  mp7Ui = new ActionFormData()
    .title("MP-7 Attachment")
    .body("")
    .button("Remove Attachment")
    .button("Add Suppressor")
});

world.afterEvents.itemUse.subscribe(({ source: player, itemStack }) => {
  switch (itemStack.typeId) {
    case 'ssia:attachment': customUi.show(player).then((
      { canceled, selection }) => {
      if (canceled) return;
      let response = selection
      switch (response) {
        case 0:
          mp7Ui.show(player).then(({
            canceled, selection
          }) => {
            if (canceled) return;
            if (selection === 0) system.run(() => player.runCommand('function attachment/removeMp7'))
            if (selection === 1) system.run(() => player.runCommand('function attachment/addMp7'))
          })
          break;
        case 1:
          scarUi.show(player).then(({
            canceled, selection
          }) => {
            if (canceled) return;
            if (selection === 0) system.run(() => player.runCommand('function attachment/removeAttachment'))
            if (selection === 1) system.run(() => player.runCommand('function attachment/scar_suppressor'))
            if (selection === 2) system.run(() => player.runCommand('function attachment/scar_acog'))
            if (selection === 3) system.run(() => player.runCommand('function attachment/scar_reddot'))
            if (selection === 4) system.run(() => player.runCommand('function attachment/scar_grip'))
          })
          break;
        case 3:
          system.run(() => player.dimension.runCommand('give @s minecraft:diamond'))
      }
    })

  }
});

