import {system,BlockPermutation,world,ItemStack,GameMode} from '@minecraft/server';


/*
one day someone will see this code and say "hell yeah"
*/
export function RunicNoBreak(block)
{
    const entityOptions = {
        type:"minecraft:player",
        location: {x:block.location.x-16,y:block.location.y,z:block.location.z-16},
        volume:{x:33,y:28,z:33}
    }
    const entities = block.dimension.getEntities(entityOptions);
    for (let entity of entities) {
        if(!entity.matches({ gameMode: GameMode.Spectator }) && !entity.matches({ gameMode: GameMode.Creative }))
        {
            if(world.scoreboard.getObjective("shield").getScore(entity)==0)
            {
                entity.runCommand(`scoreboard players set @s shield 24`)
                var AreaProtectedMessage= { 
                translate: "message.AreaProtectedMessage",
                };
                entity.sendMessage(AreaProtectedMessage)
            }
            else
            {
                entity.runCommand(`scoreboard players set @s shield 12`)
            }
        }
    }
}

export function StartEnabling(block)
{
    CloseCeiling(block)
    block.dimension.playSound('respawn_anchor.set_spawn',block.center(),{pitch:1,volume:15});
    KillWaveManager(block)
    var entity = block.dimension.spawnEntity('edx:runic_wave_manager',block.bottomCenter())
    entity.setDynamicProperty('max_wave',6)
    entity.setDynamicProperty('waves',0)
    StartWave(block)
}
function CloseCeiling(block)
{
    for(let i = -3; i <= 3 ; i++) {
        system.runJob(function* () {
            for(let j = -3; j <= 3 ; j++) {
                try{
                    block.dimension.getBlock({x:block.location.x+i,y:block.location.y+13,z:block.location.z+j}).setType('edx:runic_shield')
                }
                catch(e){}
            }
        }())
    }
}
function OpenCeiling(block)
{
    for(let i = -3; i <= 3 ; i++) {
        system.runJob(function* () {
            for(let j = -3; j <= 3 ; j++) {
                try{
                    block.dimension.getBlock({x:block.location.x+i,y:block.location.y+13,z:block.location.z+j}).setType('minecraft:air')
                }
                catch(e){}
            }
        }())
    }
}
async function StartWave(block)
{
    ClearRoom(block)
    await system.waitTicks(5)
    GenerateRoom(block)
    await system.waitTicks(300)
    LightColorAround(block)
    await system.waitTicks(78)
    UnLightColorAround(block)
    block.dimension.spawnParticle('edx:blue_runic_light_shockwave_particle',block.center())
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:waves': true}));
    WaveManager(block,"blue")
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:wave_pause': false}));
}

async function LightColorAround(block)
{
    
    for(let i = 1; i <= 15 ; i++) {//16 to count bricks
        await system.waitTicks(6)
        system.runJob(function* () {
            for(let j = -Math.abs(i); j <= Math.abs(i) ; j++) {
                
                for(let k = -1; k <= 25 ; k++) {
                    yield
                    LightColor(block,i,j,k)
                }
            }
        }())
    }
    
    
}
export async function UnLightColorAround(block)
{
    for(let i = 1; i <= 16 ; i++) {
        await system.waitTicks(6)
        system.runJob(function* () {
            for(let j = -Math.abs(i); j <= Math.abs(i) ; j++) {
                for(let k = -1; k <= 25 ; k++) {
                    yield
                    UnLightColor(block,i,j,k)
                }
            }
        }())
    }
    
}
async function UnpowerAround(block)
{
    for(let i = 1; i <= 16 ; i++) {//16 to count bricks
        await system.waitTicks(6)
        system.runJob(function* () {
            for(let j = -Math.abs(i); j <= Math.abs(i) ; j++) {
                for(let k = -1; k <= 25 ; k++) {
                    yield
                    Unpower(block,i,j,k)
                }
                
            }
        }())
    }
    
}

function LightColor(block,i,j,k)
{
    try{
    const block1 =block.dimension.getBlock({x:block.location.x+i,y:block.location.y+k,z:block.location.z+j})
    const block2 =block.dimension.getBlock({x:block.location.x+j,y:block.location.y+k,z:block.location.z+i})
    const block3 =block.dimension.getBlock({x:block.location.x+j,y:block.location.y+k,z:block.location.z-i})
    const block4 =block.dimension.getBlock({x:block.location.x-i,y:block.location.y+k,z:block.location.z+j})
    if(block1.hasTag('edx:rune_change_color'))
        {block1.setPermutation(BlockPermutation.resolve(block1.typeId, {...block1.permutation.getAllStates(),'edx:light': 2}));block.dimension.spawnParticle('edx:blue_runic_light_color_particle',block1.center());}
    if(block2.hasTag('edx:rune_change_color'))
        {block2.setPermutation(BlockPermutation.resolve(block2.typeId, {...block2.permutation.getAllStates(),'edx:light': 2}));block.dimension.spawnParticle('edx:blue_runic_light_color_particle',block2.center());}
    if(block3.hasTag('edx:rune_change_color'))
        {block3.setPermutation(BlockPermutation.resolve(block3.typeId, {...block3.permutation.getAllStates(),'edx:light': 2}));block.dimension.spawnParticle('edx:blue_runic_light_color_particle',block3.center());}
    if(block4.hasTag('edx:rune_change_color'))
        {block4.setPermutation(BlockPermutation.resolve(block4.typeId, {...block4.permutation.getAllStates(),'edx:light': 2}));block.dimension.spawnParticle('edx:blue_runic_light_color_particle',block4.center());}
    }
    catch(e){}
}
function UnLightColor(block,i,j,k)
{
    try{
    const block1 =block.dimension.getBlock({x:block.location.x+i,y:block.location.y+k,z:block.location.z+j})
    const block2 =block.dimension.getBlock({x:block.location.x+j,y:block.location.y+k,z:block.location.z+i})
    const block3 =block.dimension.getBlock({x:block.location.x+j,y:block.location.y+k,z:block.location.z-i})
    const block4 =block.dimension.getBlock({x:block.location.x-i,y:block.location.y+k,z:block.location.z+j})
    if(block1.hasTag('edx:rune_change_color'))
        block1.setPermutation(BlockPermutation.resolve(block1.typeId, {...block1.permutation.getAllStates(),'edx:light': 1}));
    if(block2.hasTag('edx:rune_change_color'))
        block2.setPermutation(BlockPermutation.resolve(block2.typeId, {...block2.permutation.getAllStates(),'edx:light': 1}));
    if(block3.hasTag('edx:rune_change_color'))
        block3.setPermutation(BlockPermutation.resolve(block3.typeId, {...block3.permutation.getAllStates(),'edx:light': 1}));
    if(block4.hasTag('edx:rune_change_color'))
        block4.setPermutation(BlockPermutation.resolve(block4.typeId, {...block4.permutation.getAllStates(),'edx:light': 1}));
    }
    catch(e){}
}
function Unpower(block,i,j,k)
{
    try{
    const block1 =block.dimension.getBlock({x:block.location.x+i,y:block.location.y+k,z:block.location.z+j})
    const block2 =block.dimension.getBlock({x:block.location.x+j,y:block.location.y+k,z:block.location.z+i})
    const block3 =block.dimension.getBlock({x:block.location.x+j,y:block.location.y+k,z:block.location.z-i})
    const block4 =block.dimension.getBlock({x:block.location.x-i,y:block.location.y+k,z:block.location.z+j})
    if(block1.hasTag('edx:rune_change_color'))
        block1.setPermutation(BlockPermutation.resolve(block1.typeId, {...block1.permutation.getAllStates(),'edx:light': 0}));
    if(block2.hasTag('edx:rune_change_color'))
        block2.setPermutation(BlockPermutation.resolve(block2.typeId, {...block2.permutation.getAllStates(),'edx:light': 0}));
    if(block3.hasTag('edx:rune_change_color'))
        block3.setPermutation(BlockPermutation.resolve(block3.typeId, {...block3.permutation.getAllStates(),'edx:light': 0}));
    if(block4.hasTag('edx:rune_change_color'))
        block4.setPermutation(BlockPermutation.resolve(block4.typeId, {...block4.permutation.getAllStates(),'edx:light': 0}));
    }
    catch(e){}
}




function ClearRoom(block)
{
    const location = block.location
    block.dimension.runCommand(`structure load blue_runic_reset ${location.x-15} ${location.y} ${location.z-15} 0_degrees none`)
    block.dimension.runCommand(`structure load blue_runic_reset2 ${location.x-11} ${location.y+11} ${location.z-11} 0_degrees none`)
}
function GenerateRoom(block)
{
    const location = block.location
    block.dimension.runCommand(`structure load ${GetBlueStructure()} ${location.x-15} ${location.y} ${location.z-15} 0_degrees none block_by_block 20 `)
    block.dimension.runCommand(`structure load ${GetBlueStructure()} ${location.x+1} ${location.y} ${location.z+1} 180_degrees none block_by_block 20 `)
    block.dimension.runCommand(`structure load ${GetBlueStructure()} ${location.x-15} ${location.y} ${location.z+1} 270_degrees none block_by_block 20 `)
    block.dimension.runCommand(`structure load ${GetBlueStructure()} ${location.x+1} ${location.y} ${location.z-15} 90_degrees none block_by_block 20 `)
}

function GetBlueStructure()
{
    
    return "blue_runic_" +Math.round((Math.random()*9)+1).toString()
}



function GetWaveData(block)
{
    var entities = block.dimension.getEntities({
        type:  "edx:runic_wave_manager",
        location: block.location,
        maxDistance: 1
    });
    for (let entity of entities) {
        return [entity.getDynamicProperty('waves'),entity.getDynamicProperty('max_wave')]
    }
}
export function KillWaveManager(block)
{
    var entities = block.dimension.getEntities({
        type:  "edx:runic_wave_manager",
        location: block.location,
        maxDistance: 1
    });
    for (let entity of entities) {
       entity.remove()
    }
}

function SendChat(block,wave,max_wave,color)
{
    if(color=="blue")
    {
        var entities = block.dimension.getEntities({
            type:  "minecraft:player",
            location: {x:block.location.x-16,y:block.location.y,z:block.location.z-16},
            volume:{x:32,y:17,z:32}
        });
        for (let entity of entities) {
                    var BlueWaveMessage= {rawtext :[
      {text:"§b"},{translate: "message.WaveMessage"},{text:" "},{text: wave.toString()},{text:"/"},{ text: max_wave.toString()}
        ]};
            entity.sendMessage(BlueWaveMessage)
        }
    }
    else if(color=="red")
    {       
        var entities = block.dimension.getEntities({
            type:  "minecraft:player",
            location: {x:block.location.x-16,y:block.location.y,z:block.location.z-16},
            volume:{x:32,y:17,z:32}
        });
        for (let entity of entities) {
        var RedWaveMessage= {rawtext :[
      {text:"§v"},{translate: "message.WaveMessage"},{text:" "},{text: wave.toString()},{text:"/"},{ text: max_wave.toString()}
]};
            entity.sendMessage(RedWaveMessage)
            
        }
    }
}





export function CheckNumberOfMobs(block)
{
    var entities = block.dimension.getEntities({
        families:  ["runic"],
        location: {x:block.location.x-16,y:block.location.y,z:block.location.z-16},
        volume:{x:32,y:17,z:32}
    });
    for (let entity of entities) {
        return true
    }
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:wave_pause': true}));
    EndWave(block,"blue")
    return false
}

//keep failing when playing
//keep working when testing
export function CheckPlayers(block)
{
    const player_check = block.permutation?.getState('edx:player_check')
    var entities = block.dimension.getEntities({
        type:  "minecraft:player",
        location: {x:block.location.x-16,y:block.location.y,z:block.location.z-16},
        volume:{x:32,y:17,z:32}
    });
    for (let entity of entities) {
        if(player_check!=0)
            block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:player_check': 0}));
        return true
    }
    
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:player_check': player_check+1}));
    if(player_check+1==5)
    {
        KillMobs(block)
        ClearRoom(block)
        KillWaveManager(block)
        DestroyTables(block)
        OpenCeiling(block)
        block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:wave_pause': false,'edx:rune': false,'edx:waves': false,'edx:powered':true,'edx:wave_end': false,'edx:player_check':0}));
    }
    return false
}

function KillMobs(block)
{
    var entities = block.dimension.getEntities({
        families:  ["runic"],
        location: {x:block.location.x-16,y:block.location.y,z:block.location.z-16},
        volume:{x:32,y:17,z:32}
    });
    for (let entity of entities) {
        entity.remove()
    }
}
async function EndWave(block,color)
{
    
    const waveData = GetWaveData(block)
    SpawnXP(block,waveData[0])
    if(color=="blue")
        block.dimension.spawnParticle('edx:blue_runic_light_shockwave_particle',block.center())
    else if(color=="red")
        block.dimension.spawnParticle('edx:red_runic_light_shockwave_particle',block.center())
    await system.waitTicks(40)//prevent player from falling directly from structures
    if(waveData[0]==waveData[1])
    {
        if(color=="blue")
            BlueEndWaves(block)
        else if(color=="red")
            RedEndWaves(block)
    }
    else
    {
        block.dimension.playSound('random.levelup',block.center(),{pitch:1,volume:15});
        if(color=="blue")
            StartWave(block)
        else if(color=="red")
            RedStartWave(block)
        
    }
}
function BlueEndWaves(block)
{
    ClearRoom(block)
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:wave_end': true,'edx:waves': false,'edx:rune': false}));
    var item =block.dimension.spawnItem(new ItemStack('edx:blue_blank_runestone',1),block.above().center())
    item.clearVelocity()
    block.dimension.playSound('vault.eject_item',block.center(),{pitch:1.6,volume:15});
    block.dimension.playSound('block.runic_table.waves_finished',block.center(),{pitch:1,volume:15});
    block.west(2).north(2).setType('edx:deterioration_interpreter')
    block.west(2).south(2).setType('edx:restful_interpreter')
    block.east(2).south(2).setType('edx:restoration_interpreter')
    block.east(2).north(2).setType('edx:deprivation_interpreter')
}

function DestroyTables(block)
{
    block.west(2).north(2).setType('minecraft:air')
    block.west(2).south(2).setType('minecraft:air')
    block.east(2).south(2).setType('minecraft:air')
    block.east(2).north(2).setType('minecraft:air')
}



//rewards

export async function TpHome(block,player)
{
    KillWaveManager(block)
    DestroyTables(block)
    const equipment = player.getComponent('equippable'); 
    equipment.setEquipment('Mainhand', undefined);  
    block.dimension.spawnParticle('edx:blue_runic_light_shockwave_particle',block.center())
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:powered': false,'edx:wave_end': false,'edx:rune': false,'edx:can_diamond':false}));
    UnpowerAround(block)
    OpenCeiling(block)
    await system.waitTicks(160)
    
    var entities = block.dimension.getEntities({
        type:  "minecraft:player",
        location: {x:block.location.x-16,y:block.location.y,z:block.location.z-16},
        volume:{x:32,y:17,z:32}
    });
    for (let entity of entities) {
        block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:can_diamond':true}));
        var spawnpoint = entity.getSpawnPoint()
        if(spawnpoint==undefined)
        {
            spawnpoint=world.getDefaultSpawnLocation()
            entity.teleport({x:spawnpoint.x,y:200,z:spawnpoint.z})
            entity.addEffect('slow_falling',420)
        }
        else
        {
            entity.teleport({x:spawnpoint.x,y:spawnpoint.y,z:spawnpoint.z},{dimension:spawnpoint.dimension})
        }
    }
}

export async function RestorationTables(block,player)
{
    KillWaveManager(block)
    DestroyTables(block)
    const equipment = player.getComponent('equippable'); 
    equipment.setEquipment('Mainhand', undefined);  
    block.west(3).setType('edx:restoration_table')
    block.south(3).setType('edx:restoration_table')
    block.east(3).setType('edx:restoration_table')
    block.north(3).setType('edx:restoration_table')
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:restoration': true}));
  
}
export async function CheckRestorationTables(block)
{
    if(block.west(3).typeId=='edx:restoration_table' || block.east(3).typeId=='edx:restoration_table' || block.south(3).typeId=='edx:restoration_table' || block.north(3).typeId=='edx:restoration_table')
        return
    block.dimension.spawnParticle('edx:blue_runic_light_shockwave_particle',block.center())
    block.dimension.playSound('block.runic_table.turn_off',block.center(),{pitch:1,volume:15});
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:powered': false,'edx:wave_end': false,'edx:rune': false,'edx:restoration': false}));
    UnpowerAround(block)
    OpenCeiling(block)
}

//for dumbasses without tools or weapons, who is doing this structure naked?
export async function SkipRestorationTables(block)
{
    block.west(3).setType('minecraft:air')
    block.south(3).setType('minecraft:air')
    block.east(3).setType('minecraft:air')
    block.north(3).setType('minecraft:air')
    block.dimension.playSound('block.runic_table.turn_off',block.center(),{pitch:1,volume:15});
    block.dimension.spawnParticle('edx:blue_runic_light_shockwave_particle',block.center())
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:powered': false,'edx:wave_end': false,'edx:rune': false,'edx:restoration': false}));
    UnpowerAround(block)
    OpenCeiling(block)
}

export async function PurpleRuneStone(block,player)
{
    const equipment = player.getComponent('equippable'); 
    equipment.setEquipment('Mainhand', new ItemStack('edx:runestone',1));   
    KillWaveManager(block)
    DestroyTables(block)
    block.dimension.playSound('block.runic_table.turn_off',block.center(),{pitch:1,volume:15});
    block.dimension.spawnParticle('edx:blue_runic_light_shockwave_particle',block.center())
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:powered': false,'edx:wave_end': false,'edx:rune': false}));
    OpenCeiling(block)
    UnpowerAround(block)
    
  
}
export async function DestroyStructure(block,player)
{
    KillWaveManager(block)
    DestroyTables(block)
    const equipment = player.getComponent('equippable'); 
    equipment.setEquipment('Mainhand', undefined);  
    block.dimension.playSound('block.runic_table.turn_off',block.center(),{pitch:1,volume:15});
    block.dimension.spawnParticle('edx:blue_runic_light_shockwave_particle',block.center())
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:powered': false,'edx:wave_end': false,'edx:rune': false,'edx:can_diamond':false}));
    UnpowerAround(block)
    OpenCeiling(block)
    await system.waitTicks(160)
    block.setType('minecraft:air')
    block.dimension.spawnParticle('edx:runic_destroy',block.center())
    
    DecayStructure(block)
    
  
}
async function DecayStructure(block)
{
    for(let i = 0; i <= 16 ; i++) {
        await system.waitTicks(6)
        system.runJob(function* () {
            for(let j = -Math.abs(i); j <= Math.abs(i) ; j++) {
                for(let k = -1; k <= 25 ; k++) {
                    yield
                    DecayBlock(block,i,j,k)
                }
            }
        }())
    }
}

function DecayBlock(block,i,j,k)
{
    const block1 =block.dimension.getBlock({x:block.location.x+i,y:block.location.y+k,z:block.location.z+j})
    const block2 =block.dimension.getBlock({x:block.location.x+j,y:block.location.y+k,z:block.location.z+i})
    const block3 =block.dimension.getBlock({x:block.location.x+j,y:block.location.y+k,z:block.location.z-i})
    const block4 =block.dimension.getBlock({x:block.location.x-i,y:block.location.y+k,z:block.location.z+j})
    if(block1.hasTag('edx:runic'))
        block1.setPermutation(BlockPermutation.resolve(block1.typeId, {...block1.permutation.getAllStates(),'edx:decay': true}));
    if(block2.hasTag('edx:runic'))
        block2.setPermutation(BlockPermutation.resolve(block2.typeId, {...block2.permutation.getAllStates(),'edx:decay': true}));
    if(block3.hasTag('edx:runic'))
        block3.setPermutation(BlockPermutation.resolve(block3.typeId, {...block3.permutation.getAllStates(),'edx:decay': true}));
    if(block4.hasTag('edx:runic'))
        block4.setPermutation(BlockPermutation.resolve(block4.typeId, {...block4.permutation.getAllStates(),'edx:decay': true}));
}

export function Continue(block,player)
{
    const equipment = player.getComponent('equippable'); 
    equipment.setEquipment('Mainhand', undefined);  
    var entities = block.dimension.getEntities({
        type:  "edx:runic_wave_manager",
        location: block.location,
        maxDistance: 1
    });
    for (let entity of entities) {
        entity.setDynamicProperty('max_wave',entity.getDynamicProperty('max_wave')+8)
    }
    block.dimension.spawnParticle('edx:blue_runic_light_shockwave_particle',block.center())
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:waves': true,'edx:wave_end':false,'edx:rune':true}));
    DestroyTables(block)
    var entities = block.dimension.getEntities({
        type:  "minecraft:player",
        location: {x:block.location.x-16,y:block.location.y,z:block.location.z-16},
        volume:{x:32,y:17,z:32}
    });
    for (let entity of entities) {
       var BlueContinueMessage= {rawtext :[
      {text:"§b"},{translate: "message.ContinueMessage"}
        ]};
     entity.sendMessage(BlueContinueMessage)
    }
    StartWave(block)
}

function SpawnXP(block,wave)
{
    for(let i = 0; i < Math.min(80,8+wave*2) ; i++)
        block.dimension.spawnEntity("xp_orb",block.above().center());
}


//waves
const blueWave1 = ["edx:baste","edx:sentinel"]//wave 1, voluntary easy
//start at wave 2
//number of mobs = initial number/numberDivided, for fairness because fighting 40 bondlings isn't fun
const blueWaves = 
[
    //bondling party
    {
        weight:20,
        normal:["edx:bondling"],
        hard:["edx:bondling","edx:bondling","edx:bondling","edx:enlighter"],
        void:["edx:bondling","edx:bondling","edx:enlighter"],
        numberDivided:1.5
    },
    //baste party
    {
        weight:20,
        normal:["edx:baste"],
        hard:["edx:baste","edx:baste","edx:baste","edx:enlighter"],
        void:["edx:baste","edx:baste","edx:enlighter"],
        numberDivided:1.7
    },
    //aerial
    {
        weight:40,
        normal:["edx:baste","edx:bondling"],
        hard:["edx:baste","edx:bondling","edx:enlighter"],
        void:["edx:baste","edx:bondling","edx:enlighter"],
        numberDivided:1.4
    },
    //ground
    {
        weight:40,
        normal:["edx:sentinel","edx:sentinel","edx:sentinel","edx:oculus","edx:enlighter"],
        hard:["edx:sentinel","edx:sentinel","edx:sentinel","edx:oculus","edx:enlighter","edx:caretaker"],
        void:["edx:sentinel","edx:sentinel","edx:sentinel","edx:oculus","edx:enlighter","edx:caretaker"],
        numberDivided:1
    },
    //sniper
    {
        weight:10,
        normal:["edx:oculus"],
        hard:["edx:oculus","edx:oculus","edx:enlighter"],
        void:["edx:oculus","edx:oculus","edx:enlighter"],
        numberDivided:1.2
    },
    //like the wave 1
    {
        weight:20,
        normal:["edx:sentinel","edx:sentinel","edx:baste"],
        hard:["edx:sentinel","edx:sentinel","edx:baste","edx:enlighter"],
        void:["edx:sentinel","edx:baste","edx:enlighter"],
        numberDivided:1
    },
    //ball and rod
    {
        weight:20,
        normal:["edx:bondling","edx:bondling","edx:oculus"],
        hard:["edx:bondling","edx:bondling","edx:oculus","edx:enlighter"],
        void:["edx:bondling","edx:bondling","edx:oculus","edx:enlighter"],
        numberDivided:1
    },
    //russian roulette
    {
        weight:10,
        normal:["edx:sentinel","edx:sentinel","edx:sentinel","edx:sentinel","edx:sentinel","edx:caretaker"],
        hard:["edx:sentinel","edx:sentinel","edx:sentinel","edx:sentinel","edx:bondling","edx:caretaker"],
        void:["edx:sentinel","edx:sentinel","edx:sentinel","edx:bondling","edx:bondling","edx:caretaker"],
        numberDivided:1.2
    },
    //everything
    {
        weight:20,
        normal:["edx:baste","edx:sentinel","edx:bondling","edx:baste","edx:sentinel","edx:bondling","edx:oculus","edx:enlighter"],
        hard:["edx:baste","edx:sentinel","edx:bondling","edx:baste","edx:sentinel","edx:bondling","edx:oculus","edx:oculus","edx:enlighter","edx:enlighter","edx:caretaker"],
        void:["edx:baste","edx:sentinel","edx:bondling","edx:bondling","edx:baste","edx:oculus","edx:enlighter","edx:caretaker"],
        numberDivided:1.2
    }
]

//start at wave 5 in normal, 3 in hard, 1 in void
const effects =
[
    "speed",
    "resistance",
    "regeneration"
]

function WaveManager(block,color)
{
    var entities = block.dimension.getEntities({
        type:  "edx:runic_wave_manager",
        location: block.location,
        maxDistance: 1
    });
    for (let entity of entities) {
        entity.setDynamicProperty('waves',entity.getDynamicProperty('waves')==undefined?1:entity.getDynamicProperty('waves')+1)
    }
    const waveData = GetWaveData(block)
    SendChat(block,waveData[0],waveData[1],color)
    summonMobs(block,NumberOfMobs(waveData[0]),waveData[0],color,waveData[1])
    
}

function NumberOfMobs(waves)
{
    const hardMode = world?.getDynamicProperty('hard_mode')
    const voidMode = world?.getDynamicProperty('void_mode')
    const hardModeNumber =hardMode!=undefined?2:0
    const voidModeNumber =voidMode!=undefined?2:0
    return Math.min(5+(waves-1)*2+hardModeNumber+voidModeNumber,40)
}

function summonMobs(block,number,wave,color,maxWave)
{
    
    
    var x=0
    var z=0
    var offset = color=="blue"?10:color=="red"?0:0
    var radiusStart = color=="blue"?4:color=="red"?8:0
    var radius = color=="blue"?9:color=="red"?2:0
    var effect = GetEffect(wave)
    var WaveType = GetWaveType(wave,color)
    if(color=="red" && wave==maxWave)
    {
        for (var i=0;i<4;i++) {
        x=9
        z=9
        x*=i%2?1:-1 //répartir dans les 4 coins
        z*=Math.floor(i/2+1)%2?1:-1
        const newblock = block.dimension.getBlockFromRay({x:block.x+x,y:block.y+offset,z:block.z+z},{x:0,y:-1,z:0},{maxDistance:25})?.block
        if(newblock!=undefined)
           i = SpawnMob(newblock.above(),i,['edx:behemoth'],effect);
        }
    }
    else
        for (var i=0;i<Math.ceil(number/WaveType[1]);i++) {
            x=(radiusStart+Math.random()*radius)
            z=(radiusStart+Math.random()*radius)
            x*=i%2?1:-1 //répartir dans les 4 coins
            z*=Math.floor(i/2+1)%2?1:-1
            const newblock = block.dimension.getBlockFromRay({x:block.x+x,y:block.y+offset,z:block.z+z},{x:0,y:-1,z:0},{maxDistance:25})?.block
            if(newblock!=undefined)
            i = SpawnMob(newblock.above(),i,WaveType[0],effect);
        }
}

function SpawnMob(block,i,mobs,effect){
    const mob = mobs[Math.round(Math.random()*(mobs.length-1))]
    if(mob=="edx:bondling") {i+=1;var entity2 = block.dimension.spawnEntity(mob,block.center())}//spawn a second bondling + increasing the counter to count the new bondling
    if(mob=="edx:blame_thrower") {block = block.dimension.getBlockFromRay({x:block.x,y:block.y,z:block.z},{x:0,y:1,z:0},{maxDistance:35})?.block?.below(2)}
    try{
        var entity = block.dimension.spawnEntity(mob,block.center())
        if(effect!=false)
        {
            entity.addEffect(effect,20000000,{amplifier:0})//need to change the system for amplifier !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            entity2?.addEffect(effect,20000000,{amplifier:0})
        }
    }catch(e){}
    return i
}

function GetEffect(wave)
{
    const hardMode = world?.getDynamicProperty('hard_mode')
    const voidMode = world?.getDynamicProperty('void_mode')
    if(voidMode ||(hardMode && wave>=4)||(wave>=8))
    {
        return effects[Math.round((Math.random()*(effects.length-1)))]
    }
    return false
}

function GetWaveType(wave,color)
{
    if(wave==1 && color=="blue") return [blueWave1,1]
    if(wave==1 && color=="red") return [redWave1,1]
    var waves = color=="blue"?blueWaves:redWaves
    const hardMode = world?.getDynamicProperty('hard_mode')
    const voidMode = world?.getDynamicProperty('void_mode')
    var weightsum=0
    for (const type of waves)
    {
        weightsum+=type.weight
    }
    const randomNumber = Math.random()*weightsum
    var weightcount =0
    var wavechosenidx = 0
    for (var i = 0; i < waves.length; i++)
    {
        weightcount+=waves[i].weight
        if (randomNumber <= weightcount) {
            wavechosenidx = i;
            break;
        }
    }
    if(voidMode)
        return [waves[wavechosenidx].void,waves[wavechosenidx].numberDivided]
    else if(hardMode)
        return [waves[wavechosenidx].hard,waves[wavechosenidx].numberDivided]
    else
        return [waves[wavechosenidx].normal,waves[wavechosenidx].numberDivided]
}



//red runic 


export async function RedObeliskDestroy(block,structure)
{

    
    DestroyObelisk(block)
    if(!structure) return
    await system.waitTicks(60)
    if(block.dimension.id=="minecraft:nether")
    {
        block.dimension.runCommand(`structure load red_runic_arena ${block.location.x-29} 28 ${block.location.z-29}`)
    }
}

async function DestroyObelisk(block)
{
    
    for(let i = 0; i <= 3 ; i++) {
        system.runJob(function* () {
            for(let j = -Math.abs(i); j <= Math.abs(i) ; j++) {
                yield
                for(let k = -5; k <= 14 ; k++) {
                    
                    DecayBlock(block,i,j,k)
                }
            }
        }())
    }
}
async function DigDown(block)
{
    
    for(let i = -3; i <= 3 ; i++) {
        system.runJob(function* () {
            for(let j = -3; j <= 3 ; j++) {
                yield
                for(let k = 28-block.location.y; k <= -5 ; k++) {
                    const block1 = block.dimension.getBlock({x:block.location.x+i,y:block.location.y+k,z:block.location.z+j})
                    if(!block1.getTags().includes('edx:runic'))
                        block1.setType('minecraft:air')
                }
            }
        }())
    }
}

export function RedRunicNoBreak(block)
{
    const entityOptions = {
        type:"minecraft:player",
        location: {x:block.location.x-25,y:block.location.y-13,z:block.location.z-25},
        volume:{x:51,y:19,z:51}
    }
    const entities = block.dimension.getEntities(entityOptions);
    for (let entity of entities) {
        if(!entity.matches({ gameMode: GameMode.Spectator }) && !entity.matches({ gameMode: GameMode.Creative }))
        {
            if(world.scoreboard.getObjective("shield").getScore(entity)==0)
            {
                entity.runCommand(`scoreboard players set @s shield 24`)
                                var AreaProtectedMessage= {rawtext :[{ 
                translate: "message.AreaProtectedMessage",
                }]};
                entity.sendMessage(AreaProtectedMessage)
            }
            else
            {
                entity.runCommand(`scoreboard players set @s shield 12`)
            }
        }
    }
}

export function RedStartEnabling(block)
{
    BlockDoors(block)
    block.dimension.playSound('respawn_anchor.set_spawn',block.center(),{pitch:1,volume:15});
    KillWaveManager(block)
    var entity = block.dimension.spawnEntity('edx:runic_wave_manager',block.bottomCenter())
    entity.setDynamicProperty('max_wave',6)
    entity.setDynamicProperty('waves',0)
    RedStartWave(block)
}

function BlockDoors(block)
{
    for(let i = -6; i <= 6 ; i++) {
        for(let k = -13; k <= -6 ; k++) {
            var block1 = block.dimension.getBlock({x:block.location.x+i,y:block.location.y+k,z:block.location.z+20})
            if(block1.typeId=="minecraft:air")
                block1.setType('edx:red_runic_shield')
            block1 = block.dimension.getBlock({x:block.location.x+i,y:block.location.y+k,z:block.location.z-20})
            if(block1.typeId=="minecraft:air")
                block1.setType('edx:red_runic_shield')
            block1 = block.dimension.getBlock({x:block.location.x+20,y:block.location.y+k,z:block.location.z+i})
            if(block1.typeId=="minecraft:air")
                block1.setType('edx:red_runic_shield')
            block1 = block.dimension.getBlock({x:block.location.x-20,y:block.location.y+k,z:block.location.z+i})
            if(block1.typeId=="minecraft:air")
                block1.setType('edx:red_runic_shield')
        }
            
    }
}
function UnBlockDoors(block)
{
    for(let i = -6; i <= 6 ; i++) {
        for(let k = -13; k <= -6 ; k++) {
            var block1 = block.dimension.getBlock({x:block.location.x+i,y:block.location.y+k,z:block.location.z+20})
            if(block1.typeId=="edx:red_runic_shield")
                block1.setType('minecraft:air')
            block1 = block.dimension.getBlock({x:block.location.x+i,y:block.location.y+k,z:block.location.z-20})
            if(block1.typeId=="edx:red_runic_shield")
                block1.setType('minecraft:air')
            block1 = block.dimension.getBlock({x:block.location.x+20,y:block.location.y+k,z:block.location.z+i})
            if(block1.typeId=="edx:red_runic_shield")
                block1.setType('minecraft:air')
            block1 = block.dimension.getBlock({x:block.location.x-20,y:block.location.y+k,z:block.location.z+i})
            if(block1.typeId=="edx:red_runic_shield")
                block1.setType('minecraft:air')
        }
            
    }
}

async function RedStartWave(block)
{
    const waveData = GetWaveData(block)
    await system.waitTicks(80)
    RedUnIgnite(block)
    await system.waitTicks(40)
    RedIgnite(block,waveData[0])
    await system.waitTicks(100)
    RedLightColorAround(block)
    await system.waitTicks(140)
    RedUnLightColorAround(block)
    block.dimension.spawnParticle('edx:red_runic_light_shockwave_particle',block.center())
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:waves': true}));
    WaveManager(block,"red")
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:wave_pause': false}));
}

async function RedLightColorAround(block)
{
    
    for(let i = 0; i <= 23 ; i++) {
        await system.waitTicks(6)
        system.runJob(function* () {
            for(let j = -Math.abs(i); j <= Math.abs(i) ; j++) {
                
                for(let k = -14; k <= 6 ; k++) {
                    yield
                    RedLightColor(block,i,j,k)
                }
            }
        }())
    }
    
    
}
export async function RedUnLightColorAround(block)
{
    for(let i = 0; i <= 23 ; i++) {
        await system.waitTicks(6)
        system.runJob(function* () {
            for(let j = -Math.abs(i); j <= Math.abs(i) ; j++) {
                for(let k = -14; k <= 6 ; k++) {
                    yield
                    UnLightColor(block,i,j,k)
                }
            }
        }())
    }
    
}
async function RedUnpowerAround(block)
{
    for(let i = 0; i <= 23 ; i++) {
        await system.waitTicks(6)
        system.runJob(function* () {
            for(let j = -Math.abs(i); j <= Math.abs(i) ; j++) {
                for(let k = -14; k <= 6 ; k++) {
                    yield
                    Unpower(block,i,j,k)
                }
                
            }
        }())
    }
    
}

function RedLightColor(block,i,j,k)
{
    try{
    const block1 =block.dimension.getBlock({x:block.location.x+i,y:block.location.y+k,z:block.location.z+j})
    const block2 =block.dimension.getBlock({x:block.location.x+j,y:block.location.y+k,z:block.location.z+i})
    const block3 =block.dimension.getBlock({x:block.location.x+j,y:block.location.y+k,z:block.location.z-i})
    const block4 =block.dimension.getBlock({x:block.location.x-i,y:block.location.y+k,z:block.location.z+j})
    if(block1.hasTag('edx:rune_change_color'))
        {block1.setPermutation(BlockPermutation.resolve(block1.typeId, {...block1.permutation.getAllStates(),'edx:light': 2}));block.dimension.spawnParticle('edx:red_runic_light_color_particle',block1.center());}
    if(block2.hasTag('edx:rune_change_color'))
        {block2.setPermutation(BlockPermutation.resolve(block2.typeId, {...block2.permutation.getAllStates(),'edx:light': 2}));block.dimension.spawnParticle('edx:red_runic_light_color_particle',block2.center());}
    if(block3.hasTag('edx:rune_change_color'))
        {block3.setPermutation(BlockPermutation.resolve(block3.typeId, {...block3.permutation.getAllStates(),'edx:light': 2}));block.dimension.spawnParticle('edx:red_runic_light_color_particle',block3.center());}
    if(block4.hasTag('edx:rune_change_color'))
        {block4.setPermutation(BlockPermutation.resolve(block4.typeId, {...block4.permutation.getAllStates(),'edx:light': 2}));block.dimension.spawnParticle('edx:red_runic_light_color_particle',block4.center());}
    }
    catch(e){}
}

async function RedUnIgnite(block)
{
    
    for(let i = -19; i <= 19 ; i++) {
        system.runJob(function* () {
            for(let j = -19; j <= 19 ; j++) {
                
                for(let k = -19; k <= 0 ; k++) {
                    yield
                   const block1 =block.dimension.getBlock({x:block.location.x+i,y:block.location.y+k,z:block.location.z+j})
                    if(block1.typeId == 'edx:polished_red_runic_stone')
                        {block1.setPermutation(BlockPermutation.resolve(block1.typeId, {...block1.permutation.getAllStates(),'edx:light': 0}));}
                }
            }
        }())
    }
    
    
}
async function RedIgnite(block,wave)
{
    const height = -14 + Math.min(Math.round(wave/2),6)-1
    block.dimension.spawnParticle('edx:red_runic_ignite_plan',{x:block.center().x,y:block.location.y+height+1.5,z:block.center().z})
    await system.waitTicks(100)
    for(let i = -19; i <=  19 ; i++) {
        system.runJob(function* () {
            for(let j = -19; j <= 19 ; j++) {
                
                for(let k = -14; k <= height ; k++) {
                    yield
                   const block1 =block.dimension.getBlock({x:block.location.x+i,y:block.location.y+k,z:block.location.z+j})
                    if(block1.typeId == 'edx:polished_red_runic_stone')
                        {block1.setPermutation(BlockPermutation.resolve(block1.typeId, {...block1.permutation.getAllStates(),'edx:light': 1}));}
                }
            }
        }())
    }
}

export function RedCheckNumberOfMobs(block)
{
    var entities = block.dimension.getEntities({
        families:  ["runic"],
        location: {x:block.location.x-19,y:block.location.y-13,z:block.location.z-19},
        volume:{x:39,y:19,z:39}
    });
    for (let entity of entities) {
        return true
    }
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:wave_pause': true}));
    EndWave(block,"red")
    return false
}
export function RedCheckPlayers(block)
{
    const player_check = block.permutation?.getState('edx:player_check')
    var entities = block.dimension.getEntities({
        type:  "minecraft:player",
        location: {x:block.location.x-19,y:block.location.y-13,z:block.location.z-19},
        volume:{x:39,y:19,z:39}
    });
    for (let entity of entities) {
        if(player_check!=0)
            block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:player_check': 0}));
        return true
    }
    
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:player_check': player_check+1}));
    if(player_check+1==5)
    {
        RedKillMobs(block)
        UnBlockDoors(block)
        KillWaveManager(block)
        block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:wave_pause': false,'edx:rune': false,'edx:waves': false,'edx:powered':true,'edx:wave_end': false,'edx:player_check':0}));
    }
   
    return false
}

function RedKillMobs(block)
{
    var entities = block.dimension.getEntities({
        families:  ["runic"],
        location: {x:block.location.x-19,y:block.location.y-13,z:block.location.z-19},
        volume:{x:39,y:19,z:39}
    });
    for (let entity of entities) {
        entity.remove()
    }
}
//waves
const redWave1 = ["edx:spark_plug","edx:enlightened"]//wave 1, voluntary easy
//start at wave 2
//number of mobs = initial number/numberDivided, for fairness because fighting 40 bondlings isn't fun
const redWaves = 
[
    //spark party
    {
        weight:20,
        normal:["edx:spark_plug"],
        hard:["edx:spark_plug"],
        void:["edx:spark_plug","edx:spark_plug","edx:blame_thrower"],
        numberDivided:1
    },
    //whooper party
    {
        weight:20,
        normal:["edx:whomper","edx:whomper","edx:blame_thrower"],
        hard:["edx:whomper","edx:whomper","edx:blame_thrower"],
        void:["edx:whomper","edx:blame_thrower"],
        numberDivided:1.2
    },

    {
        weight:40,
        normal:["edx:spark_plug","edx:rocket_walker","edx:blame_thrower"],
        hard:["edx:spark_plug","edx:rocket_walker","edx:blame_thrower"],
        void:["edx:spark_plug","edx:rocket_walker","edx:blame_thrower"],
        numberDivided:1.4
    },
    
    {
        weight:40,
        normal:["edx:spark_plug","edx:enlightened","edx:whomper","edx:blame_thrower"],
        hard:["edx:spark_plug","edx:enlightened","edx:whomper","edx:blame_thrower"],
        void:["edx:spark_plug","edx:enlightened","edx:whomper","edx:blame_thrower"],
        numberDivided:1
    },
    {
        weight:40,
        normal:["edx:spark_plug","edx:enlightened","edx:enlightened","edx:blame_thrower"],
        hard:["edx:spark_plug","edx:enlightened","edx:enlightened","edx:blame_thrower"],
        void:["edx:spark_plug","edx:spark_plug","edx:enlightened","edx:blame_thrower"],
        numberDivided:1
    },
    //rocket walker party
    {
        weight:10,
        normal:["edx:rocket_walker","edx:rocket_walker","edx:blame_thrower"],
        hard:["edx:rocket_walker","edx:rocket_walker","edx:blame_thrower"],
        void:["edx:rocket_walker","edx:blame_thrower"],
        numberDivided:1.2
    },
    //like the wave 1
    {
        weight:20,
        normal:["edx:spark_plug","edx:enlightened","edx:blame_thrower"],
        hard:["edx:spark_plug","edx:enlightened","edx:blame_thrower"],
        void:["edx:spark_plug","edx:enlightened","edx:blame_thrower"],
        numberDivided:1
    },
    //everything
    {
        weight:20,
        normal:["edx:spark_plug","edx:enlightened","edx:rocket_walker","edx:whomper","edx:blame_thrower"],
        hard:["edx:spark_plug","edx:enlightened","edx:rocket_walker","edx:whomper","edx:blame_thrower"],
        void:["edx:spark_plug","edx:enlightened","edx:rocket_walker","edx:whomper","edx:blame_thrower","edx:behemoth"],
        numberDivided:1.2
    }
]

function RedEndWaves(block)
{
    RedUnIgnite(block)
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:wave_end': true,'edx:waves': false,'edx:rune': false}));
    var item =block.dimension.spawnItem(new ItemStack('edx:red_blank_runestone',1),block.above().center())
    item.clearVelocity()
    block.dimension.playSound('vault.eject_item',block.center(),{pitch:1.6,volume:15});
    block.dimension.playSound('block.runic_table.waves_finished',block.center(),{pitch:1,volume:15});
    block.west(3).north(3).below(2).setType('edx:red_deterioration_interpreter')
    block.west(3).south(3).below(2).setType('edx:red_unification_interpreter')
    block.east(3).south(3).below(2).setType('edx:red_restoration_interpreter')
    block.east(3).north(3).below(2).setType('edx:red_division_interpreter')
}

export function RedContinue(block,player)
{
    const equipment = player.getComponent('equippable'); 
    equipment.setEquipment('Mainhand', undefined);  
    var entities = block.dimension.getEntities({
        type:  "edx:runic_wave_manager",
        location: block.location,
        maxDistance: 1
    });
    for (let entity of entities) {
        entity.setDynamicProperty('max_wave',entity.getDynamicProperty('max_wave')+6)
    }
    block.dimension.spawnParticle('edx:blue_runic_light_shockwave_particle',block.center())
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:waves': true,'edx:wave_end':false,'edx:rune':true}));
    RedDestroyTables(block)
    var entities = block.dimension.getEntities({
        type:  "minecraft:player",
        location: {x:block.location.x-19,y:block.location.y-13,z:block.location.z-19},
        volume:{x:39,y:19,z:39}
    });
    for (let entity of entities) {
      var RedContinueMessage= {rawtext :[
      {text:"§v"},{translate: "message.ContinueMessage"}
        ]};
     entity.sendMessage(RedContinueMessage)
    }
    StartWave(block)
}

function RedDestroyTables(block)
{
    block.west(3).north(3).below(2).setType('minecraft:air')
    block.west(3).south(3).below(2).setType('minecraft:air')
    block.east(3).south(3).below(2).setType('minecraft:air')
    block.east(3).north(3).below(2).setType('minecraft:air')
}

export async function RedRestoration(block,player)
{
    KillWaveManager(block)
    RedDestroyTables(block)
    const equipment = player.getComponent('equippable'); 
    equipment.setEquipment('Mainhand', undefined);  
    block.dimension.runCommand(`structure load mending_book ${block.location.x} ${block.location.y+1} ${block.location.z}`)
    block.dimension.playSound('block.runic_table.turn_off',block.center(),{pitch:1,volume:15});
    block.dimension.spawnParticle('edx:red_runic_light_shockwave_particle',block.center())
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:powered': false,'edx:wave_end': false,'edx:rune': false}));
    UnBlockDoors(block)
    RedUnpowerAround(block)
    
  
}
export async function RedUnification(block,player)
{
    const equipment = player.getComponent('equippable'); 
    equipment.setEquipment('Mainhand', new ItemStack('edx:unifying_stone',2));   
    KillWaveManager(block)
    RedDestroyTables(block)
    block.dimension.playSound('block.runic_table.turn_off',block.center(),{pitch:1,volume:15});
    block.dimension.spawnParticle('edx:red_runic_light_shockwave_particle',block.center())
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:powered': false,'edx:wave_end': false,'edx:rune': false}));
    UnBlockDoors(block)
    RedUnpowerAround(block)
    
  
}
export async function RedDivision(block,player)
{
    KillWaveManager(block)
    RedDestroyTables(block)
    const equipment = player.getComponent('equippable'); 
    equipment.setEquipment('Mainhand', undefined);
    block.west(3).north(3).below(2).setType('edx:division_table')
    block.east(3).south(3).below(2).setType('edx:division_table')
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:division': true}));
  
}
export async function CheckDivisionTables(block)
{
    if(block.west(3).north(3).below(2).typeId=='edx:division_table' || block.east(3).south(3).below(2).typeId=='edx:division_table')
        return
    block.dimension.spawnParticle('edx:red_runic_light_shockwave_particle',block.center())
    block.dimension.playSound('block.runic_table.turn_off',block.center(),{pitch:1,volume:15});
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:powered': false,'edx:wave_end': false,'edx:rune': false,'edx:division': false}));
    UnBlockDoors(block)
    RedUnpowerAround(block)
}

//for dumbasses without tools or weapons, who is doing this structure naked?
export async function SkipDivisionTables(block)
{
    block.west(3).north(3).below(2).setType('minecraft:air')
    block.east(3).south(3).below(2).setType('minecraft:air')
    block.dimension.playSound('block.runic_table.turn_off',block.center(),{pitch:1,volume:15});
    block.dimension.spawnParticle('edx:red_runic_light_shockwave_particle',block.center())
    block.setPermutation(BlockPermutation.resolve(block.typeId, {...block.permutation.getAllStates(),'edx:powered': false,'edx:wave_end': false,'edx:rune': false,'edx:division': false}));
    UnBlockDoors(block)
    RedUnpowerAround(block)
}


//at first the structure was supposed to explode, but it was actually my pc that was exploding
export async function RedDestroyStructure(block,player)
{
    KillWaveManager(block)
    RedDestroyTables(block)
    const equipment = player.getComponent('equippable'); 
    equipment.setEquipment('Mainhand', undefined);  
    block.dimension.playSound('block.runic_table.turn_off',block.center(),{pitch:1,volume:15});
    block.dimension.spawnParticle('edx:red_runic_light_shockwave_particle',block.center())
    UnBlockDoors(block)
    block.setType('minecraft:air')
    block.dimension.spawnParticle('edx:red_runic_destroy',block.center())
    RedDecayStructure(block)
    
  
}

async function RedDecayStructure(block)
{
    
    for(let i = 0; i <= 30 ; i++) {
        system.runJob(function* () {
            for(let j = -Math.abs(i); j <= Math.abs(i) ; j++) {
                yield
                for(let k = -19; k <= 10 ; k++) {
                    Unpower(block,i,j,k)
                    DecayBlock(block,i,j,k)
                }
            }
        }())
    }
    
    
}
