import { world,ItemStack, BlockPermutation,EnchantmentType,system } from "@minecraft/server";


/*
i no longer understand this code
if only i knew a way to write things in it...
*/
const loot_tables = [
    {
        id:"a",
        loot:[
        {
            typeId: "minecraft:copper_ingot",
            weight: 5,
        },
        {
            typeId: "minecraft:iron_ingot",
            weight: 2,
        },
        {
            typeId: "minecraft:gold_ingot",
            weight: 1,
        }
      ]
    },
    {
      id:"soul_ruin",
      loot:[
      //common
      {
        typeId: "minecraft:gunpowder",
        weight: 4,
      },
      {
        typeId: "minecraft:candle",
        weight: 4,
      },
      {
        typeId: "minecraft:soul_lantern",
        weight: 4,
      },
      {
        typeId: "minecraft:netherbrick",
        weight: 4,
      },
      {
        typeId: "edx:eye_globe",
        weight: 4,
      },

        //rare
      {
        typeId: "minecraft:gold_ingot",
        weight: 3,
      },
      {
        typeId: "minecraft:burn_pottery_sherd",
        weight: 3,
      },
      {
        typeId: "minecraft:skull_pottery_sherd",
        weight: 3,
      },
      {
        typeId: "edx:solid_bone",
        weight: 3,
      },
      {
        typeId: "minecraft:enchanted_book",
        enchant:"soul_speed",
        weight: 3,
      },
        //treasure
      {
          typeId: "edx:double_soulbound_ring",
          weight: 3,
      },
      {
        typeId: "minecraft:netherite_scrap",
        weight: 1,
      },
      {
        typeId: "minecraft:golden_apple",
        weight: 1,
      },
      {
        typeId: "edx:ghast_soul",
        weight: 2,
      },
      {
        typeId: "edx:skeleton_soul",
        weight: 2,
      }
    ]
  }
    
    
];


export function chooseItemInLootTable(loot_name)//it works, idk how tho
{
    
    var loot_table = loot_tables.find(({ id }) => id === loot_name)
    var weightsum=0
    for (const item of loot_table.loot)
    {
        weightsum+=item.weight
    }
    const randomNumber = Math.random()*weightsum
    var weightcount =0
    var itemchosenidx = 0
    for (var i = 0; i < loot_table.loot.length; i++)
    {
        weightcount+=loot_table.loot[i].weight
        if (randomNumber <= weightcount) {
            itemchosenidx = i+1;
            break;
        }
    }
    if(itemchosenidx<=15)
        return [itemchosenidx,1]
    else if(itemchosenidx<=30)
    {
        return [itemchosenidx-15,2]
    }
    else if(itemchosenidx<=45)
    {
        return [itemchosenidx-30,3]
    }
}
export function getItemInLootTable(loot_name,item,itemmultiple)
{
    var loot_table = loot_tables.find(({ id }) => id === loot_name)
    const itemidx = item*itemmultiple-1
    var finalitem = new ItemStack(loot_table.loot[itemidx].typeId, 1)
    if(loot_table.loot[itemidx]?.enchant != undefined)
      finalitem.getComponent('enchantable').addEnchantments([{ type: new EnchantmentType(loot_table.loot[itemidx]?.enchant), level: 1 }])
    return finalitem
}
export function getEnchantOfItem(loot_name,item,itemmultiple)
{
    var loot_table = loot_tables.find(({ id }) => id === loot_name)
    const itemidx = item*itemmultiple-1
    if(loot_table.loot[itemidx]?.enchant != undefined)
      return loot_table.loot[itemidx]?.enchant
    else
      return undefined
}

export function noBrushTest(entity)
{
    const block = entity.dimension.getBlock(entity.location)
    var isBeingBrushed =false
    const players = block.dimension.getEntities({
        location: block.center(),
        maxDistance: 6,
        type: "player"
    });
    for (let i = 0; i < players.length ; i++)
    {
        const player = players[i]
        if(player.hasTag('brush'))
        {
            isBeingBrushed = true;
        }
            
    }
    if(isBeingBrushed == false)
    {
        const stage = block?.permutation?.getState("edx:brush_stage")
        if(stage==1)
        {
        entity.remove()
        block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:brush_stage': 0}));
        }
        else if(stage==2)
        {
            entity.triggerEvent('0');
            block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:brush_stage': 1}));
        }
        else if(stage==3)
        {
            entity.triggerEvent('1');
            block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:brush_stage': 2}));
            
        }
    }
}

export function brushItemOut()
{
  const dimensions = ['overworld', 'nether', 'the_end'].map(dim => world.getDimension(dim))
  for (const dim of dimensions){
    const sus_items = dim.getEntities({type: 'edx:sus_item'});
    for (const sus_item of sus_items){
      if(!sus_item.dimension.getBlock(sus_item.location).hasTag('edx:sus_block'))
      {
        sus_item.remove()
      }
    }
  }
}

export function brush(player){
  const options = {includePassableBlocks:true}
  if(player.hasTag('brush'))
  {
    const blockraycast = player.getBlockFromViewDirection(options)
    const block = blockraycast?.block
    const face = blockraycast?.face
    if(block!=undefined && face!=undefined)
      if(block.hasTag('edx:sus_block'))
      {
        const loot = block?.permutation?.getState("edx:loot_table")
        const stage = block?.permutation?.getState("edx:brush_stage")
        var itemidx = block?.permutation?.getState("edx:item")
        var itemmultiple = block?.permutation?.getState("edx:item_multiple")
        if(stage==0)
        {
          if(itemidx==0)
          {
            [itemidx , itemmultiple] = chooseItemInLootTable(loot)
          }
          block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:brush_stage': 1,'edx:item': itemidx,'edx:item_multiple': itemmultiple}));
            const entity = player.dimension.spawnEntity(`edx:sus_item`,block.center());
            entity.triggerEvent(`${face}`);
            entity.triggerEvent('0');
            const itemTypeId = getItemInLootTable(loot,itemidx,itemmultiple).typeId
            entity.runCommand(`replaceitem entity @s slot.weapon.mainhand 0 ${itemTypeId}`)
        }
        else if(stage==1)
        {
          const entities = block.dimension.getEntities({
            location: block.center(),
            maxDistance: 0.3,
            type: "edx:sus_item"
          });
          const entity = entities[0]
          entity.triggerEvent('1');
          block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:brush_stage': 2}));
        }
        else if(stage==2)
          {
            const entities = block.dimension.getEntities({
              location: block.center(),
              maxDistance: 0.3,
              type: "edx:sus_item"
            });
            const entity = entities[0]
            entity.triggerEvent('2');
            block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:brush_stage': 3}));
          }
        else if(stage==3)
        {
          block.dimension.playSound('dig.gravel',block.center())
          if(block.typeId == "edx:sus_soulsand")
            block.setType('minecraft:soul_sand')
          else if(block.typeId == "edx:sus_dark_gravel")
            block.setType('edx:dark_gravel')
          const entities = block.dimension.getEntities({
            location: block.center(),
            maxDistance: 0.3,
            type: "edx:sus_item"
          });
          const entity = entities[0]
          var dir={x:0,y:0,z:0}
          if(face=='Up'){
              dir = {x:0,y:1,z:0}
          }
          else if(face=='Down'){
              dir = {x:0,y:-1,z:0}
          } 
          else if(face=='North'){
              dir = {x:0,y:0,z:-1}
          }
          else if(face=='South'){
              dir = {x:0,y:0,z:1}
          }
          else if(face=='West'){
              dir = {x:-1,y:0,z:0}
          }
          else if(face=='East'){
              dir = {x:1,y:0,z:0}
          }

                                  system.runTimeout(() => {
          block.dimension.spawnItem(getItemInLootTable(loot,itemidx,itemmultiple), {x:block.center().x+dir.x,y:block.center().y+dir.y,z:block.center().z+dir.z});
                    entity.remove()
                },2)   


        }
      }
  }

}