import { world, SoundOptions, Location, BlockPermutation, Player, MinecraftEntityTypes, DynamicPropertiesDefinition } from '@minecraft/server'
import { ActionFormData, ModalFormData } from '@minecraft/server-ui'
import { getPlayerExperienceLevel } from 'get_level_tests'

world.events.worldInitialize.subscribe((eventData) => {
   let playerCompShowTick = new DynamicPropertiesDefinition()
   playerCompShowTick.defineBoolean("backpackCanTP")

   eventData.propertyRegistry.registerEntityTypeDynamicProperties(playerCompShowTick, MinecraftEntityTypes["player"])
 })

world.events.beforeItemUseOn.subscribe(use => { 
    let player = use.source, item = use.item;
    let level = player.runCommandAsync('xp 0 @s').level
    if (!player.hasTag('inUI')) {
    let blockTest = world.getDimension(player.dimension.id).getBlock(use.blockLocation);
        if (item?.typeId == 'pog:waypoint_marker' && blockTest?.typeId == 'pog:waystone') {
        UI(player)
        player.addTag('inUI');
  } else if (item?.typeId == 'pog:waypoint_marker' && player.getItemCooldown('marker') == 0 ) {
   UI2(player)
} else if (item?.typeId == 'pog:waypoint_marker' && player.getItemCooldown('marker') > 0 ){
   player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"§cYour Waystone Marker is on cooldown!"}]}`);
}
}

world.events.blockBreak.subscribe(({ block, player, brokenBlockPermutation, r }) => {
   if (brokenBlockPermutation.type.id == "pog:waystone" && player.getTags().filter(v => v.startsWith('Warp:'))) {
       const warpTags = player.getTags().filter(v => v.startsWith('Warp:'))
           for (let tag of warpTags) {
      let warpName = tag.match(/(?<=Warp:).*?(?=-)/)[0];
      let test = `Warp:${warpName}-${block.location.x}|${block.location.y}|${block.location.z}`
      player.removeTag(test)
   }}
   })

function UI2(player, entity) {
   let level = player.runCommandAsync('xp 0 @s').level
   const warpMenu = new ActionFormData()
           .title('§l§5Waystone Menu')
        const warpTags = player.getTags().filter(v => v.startsWith('Warp:'))
        for (let tag of warpTags) {
           warpMenu.button(`Overworld Waystone: §6${tag.match(/(?<=Warp:).*?(?=-)/)[0]}`);
        } if (warpTags.length > 0) {
           player.addTag('inUI');
           warpMenu.show(player).then((r) => {
              player.removeTag('inUI');
              let selectedWarp = warpTags[r.selection];
              let warpName = selectedWarp.match(/(?<=Warp:).*?(?=-)/)[0];
              const [entity] = player.dimension.getEntities({tags: [`player:${player.name}`]})
              new ActionFormData()
                 .title(`Overworld Waystone: §6${warpName}`)
                 .body('You are about to teleport to this Overworld Waystone. \n\nTeleporting to this waystone requires 3 xp levels.')
                 .button('§aTeleport to this Waystone')
                 .button('§6Remove this Waystone')
                 .show(player).then((r) => {
                    player.removeTag('inUI');
                    if (r.selection == 0 && getPlayerExperienceLevel(player) >= 3) {
                       let xCord = selectedWarp.match(/(?<=-).*?(?=\|)/)[0];
                       let yCord = selectedWarp.match(/(?<=\|).*?(?=\|)/)[0];
                       let zCord = selectedWarp.match(/[^\|]*$/)[0];
                       let d = 200;
                       let e = world.events.tick.subscribe(data => {
                          console.warn(xCord,yCord,zCord)
                          
                          player.teleport({x: Number(xCord), y: Number(yCord), z: Number(zCord)}, world.getDimension("overworld"), 0, 0)
                          player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"§aTeleported to Overworld Waystone §e${warpName}!"}]}`);
                          player.runCommandAsync('playsound mob.endermen.portal @p')
                          player.runCommandAsync(`effect @s nausea 0 255 true`);
                          player.runCommandAsync(`xp -3l @s`);
                          player.startItemCooldown('marker', 600);
                          world.events.tick.unsubscribe(e);
                       });
                    } else if (r.selection == 0 && getPlayerExperienceLevel(player) < 3) {
                           player.tell("§cYou don't have enough levels");

                  } if (r.selection == 0 && player.getDynamicProperty('busy6') == true) {
                     let xCord = selectedWarp.match(/(?<=-).*?(?=\|)/)[0];
                     let yCord = selectedWarp.match(/(?<=\|).*?(?=\|)/)[0];
                     let zCord = selectedWarp.match(/[^\|]*$/)[0];
                     let d = 200;
                     let e = world.events.tick.subscribe(data => {
                        console.warn(xCord,yCord,zCord)
                        
                        player.teleport({x: Number(xCord), y: Number(yCord), z: Number(zCord)}, world.getDimension("overworld"), 0, 0)
                        player.setDynamicProperty('tpToBountyComplete', true)
                        player.setDynamicProperty('busy6', false)
                        player.setDynamicProperty('locked6', true)
                        player.setDynamicProperty('claimed6', false)
                        player.runCommandAsync('title @p actionbar tp_end')
                        player.setDynamicProperty("betterBedrock", 2)
                        player.addTag("unlocked_7")
                        console.warn("hey")
                        player.runCommandAsync('playsound mob.endermen.portal @p')
                        player.runCommandAsync(`effect @s nausea 0 255 true`);
                        player.runCommandAsync(`xp -3l @s`);
                        player.startItemCooldown('marker', 600);
                        world.events.tick.unsubscribe(e);
                     });
                    }
                    
                    else if(r.selection == 0 && level < 3) {
                       player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"§cYou don't have enough levels!"}]}`);
                    }
                     if (r.selection == 1) {
                       player.removeTag(selectedWarp);
                       player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"§aRemoved Overworld Waystone ${warpName}!"}]}`);
                       player.runCommandAsync(`playsound note.pling @s ~~~ 1 1.5`);
                    }
                 })
           })
        } else {
           player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"§cYou have no Overworld Waystones set!"}]}`);
           player.runCommandAsync(`playsound note.pling @s ~~~ 1 0.5`);
        }
}

    function UI(player, r) {
        const warpTags = player.getTags().filter(v => v.startsWith('Warp:'))
        const blockLocation = use.blockLocation;
         new ModalFormData()
            .title('§l§aAdd a Overworld Waystone')
            .textField('§6Enter the Waystone name\n\n§7If this field is not filled, the Waystone name will be "Default".\n\nIf a name is the same as a current Waystone, the old Waystone will be overwritten.\n\n§7You have §c' + warpTags.length + '/10 Waystones set.', '   ')
            .show(player).then((r) => {
               player.removeTag('inUI');
               let warpName = r.formValues[0];
               var test = `Warp:${warpName}-${blockLocation.x}|${blockLocation.y}|${blockLocation.z}`
               if (warpName == '') warpName = 'Default';
               if (warpName.toLowerCase() == 'warp') warpName += 'ing';
               if (warpTags.find(v => v.includes(warpName))) {
                  player.removeTag(warpTags.find(v => v.includes(warpName)));
                  player.addTag(test)
                  player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"§aSet Overworld Waystone to: §e${warpName}!"}]}`);
                  player.runCommandAsync(`playsound note.pling @s ~~~ 1 1.5`);
               } else if (warpTags.length >= 10) {
                  player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"§cYou have the max amount of Overworld Waystones set already!"}]}`);
                  player.runCommandAsync(`playsound note.pling @s ~~~ 1 0.5`);
               } else {
                player.addTag(test)
                  player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"§aSet Overworld Waystone to: §e${warpName}!"}]}`);
                  player.runCommandAsync(`playsound note.pling @s ~~~ 1 1.5`);
               }
            }).catch(n=>console.error(n, n.stack));
    }
})
