import { system,world,MolangVariableMap,ItemStack,GameMode} from "@minecraft/server"
import { noBrushTest } from "./blocks/archeology_things.js";
import { BondlingLink,CaretakerLink, EnlighterLink, TestEnlighterLink } from "./entity/runic_mobs.js";


system.afterEvents.scriptEventReceive.subscribe((data) => {
  if(data.sourceEntity==undefined) return;
    let entity=data.sourceEntity;
    let location=entity.location;
    if(data.id==="edx:blazeblade_arena_manager" && entity ){
      const soul = entity.getProperty('edx:soul')
      if(!soul)
      {
        entity.dimension.spawnParticle('edx:blazeblade_flames_north',{x:entity.location.x+10.9,y:entity.location.y,z:entity.location.z});
        entity.dimension.spawnParticle('edx:blazeblade_flames_north',{x:entity.location.x-10.9,y:entity.location.y,z:entity.location.z});
        entity.dimension.spawnParticle('edx:blazeblade_flames_east',{x:entity.location.x,y:entity.location.y,z:entity.location.z+10.9});
        entity.dimension.spawnParticle('edx:blazeblade_flames_east',{x:entity.location.x,y:entity.location.y,z:entity.location.z-10.9});
        entity.dimension.spawnParticle('edx:blazeblade_small_flames',entity.location);
        entity.dimension.spawnParticle('edx:blazeblade_small_flames_inside',entity.location);
      }
      else
      {
        entity.dimension.spawnParticle('edx:soul_blazeblade_flames_north',{x:entity.location.x+10.9,y:entity.location.y,z:entity.location.z});
        entity.dimension.spawnParticle('edx:soul_blazeblade_flames_north',{x:entity.location.x-10.9,y:entity.location.y,z:entity.location.z});
        entity.dimension.spawnParticle('edx:soul_blazeblade_flames_east',{x:entity.location.x,y:entity.location.y,z:entity.location.z+10.9});
        entity.dimension.spawnParticle('edx:soul_blazeblade_flames_east',{x:entity.location.x,y:entity.location.y,z:entity.location.z-10.9});
        entity.dimension.spawnParticle('edx:soul_blazeblade_small_flames',entity.location);
        entity.dimension.spawnParticle('edx:soul_blazeblade_small_flames_inside',entity.location);
      }
      var players = entity.dimension.getPlayers({
        location: { x: entity.location.x, y: entity.location.y, z: entity.location.z },
        maxDistance: 32,
      });
      for (let player of players)
      {
        if(!player.matches({ gameMode: GameMode.Creative }) && !player.matches({ gameMode: GameMode.Spectator }))
        {
          if(player?.getDynamicProperty('blazeblade_arena')==entity.id)
          {
            if(Math.abs(entity.location.x-player.location.x)>12 || Math.abs(entity.location.z-player.location.z)>12 || entity.location.y-player.location.y>2)
            {
              player.applyDamage(2,{cause: "void",damagingEntity: undefined})
              player.playSound('mob.player.hurt_on_fire');
              BlazebladeFireLine(entity,player)
            }
            else if(Math.abs(entity.location.x-player.location.x)>22 || Math.abs(entity.location.z-player.location.z)>22)
            {
              player.applyDamage(8,{cause: "void",damagingEntity: undefined})
              player.playSound('mob.player.hurt_on_fire');
            }
          }
          else if(player?.getDynamicProperty('blazeblade_arena')==undefined && Math.abs(entity.location.x-player.location.x)<=11 || Math.abs(entity.location.z-player.location.z)<=11)
          {
            player.setDynamicProperty('blazeblade_arena',entity.id)
          }
        }
        const blazeblade = world.getEntity(entity.getDynamicProperty('id'))
        if(blazeblade!=undefined && blazeblade.dimension==entity.dimension )
        {
          if(Math.abs(entity.location.x-blazeblade.location.x)>11 || Math.abs(entity.location.z-blazeblade.location.z)>11 || entity.location.y-blazeblade.location.y>2)
            blazeblade.teleport(entity.location)
        }
        else if(blazeblade==undefined)
          entity.remove()
      }
    }
    if(data.id==="edx:blame_thrower_shoot" && entity ){
      if(entity.target==undefined) return;
      const target = entity.target
      const dist = distance(entity.location,target.getHeadLocation())
      const view = {x:(target.getHeadLocation().x-entity.location.x)/dist,y:(target.location.y+1-entity.location.y)/dist,z:(target.getHeadLocation().z-entity.location.z)/dist}
      const position1 = { x: entity.location.x + view.x*2, y: entity.location.y + view.y*2, z: entity.location.z + view.z*2}
      entity.dimension.spawnEntity('edx:red_runic_fireball',position1).getComponent("minecraft:projectile").shoot(view);
    }
    if(data.id==="edx:test_enlighter_link" && entity ){
      TestEnlighterLink(entity)
    }
    if(data.id==="edx:enlighter_link" && entity ){
      EnlighterLink(entity)
    }
    if(data.id==="edx:bondling_mommy_spawn" && entity ){
      if(!entity.getProperty('edx:has_called_mommy'))
      {
        entity.dimension.spawnEntity('edx:caretaker',entity.location)
        entity.setProperty('edx:has_called_mommy',true)
      }
    }
    if(data.id==="edx:bondling_attack" && entity ){
      entity.applyKnockback({x:-entity.getViewDirection().x*2,z:-entity.getViewDirection().z*2}, 0.4)
    }
    if(data.id==="edx:bondling_link" && entity ){
      BondlingLink(entity)
    }
    if(data.id==="edx:caretaker_link" && entity ){
      CaretakerLink(entity)
    }
    if(data.id==="edx:baste_dash" && entity ){
      entity.applyKnockback({x:(Math.random()*2-1)*4,z: (Math.random()*2-1)*4}, 0)
      entity.dimension.playSound('mob.baste.dash',entity.location)
    }
    if(data.id==="edx:baste_ground" && entity ){
      entity.applyKnockback({x:0,z:0}, 1)
    }
    if(data.id==="edx:baste_shoot" && entity ){
      if(entity.target==undefined)return;
      const view = entity.getViewDirection()
      const head = entity.getHeadLocation()
      const position1 = { x: head.x + view.x, y: head.y + view.y, z: head.z + view.z}
      entity.dimension.spawnEntity('edx:baste_laser',position1).getComponent("minecraft:projectile").shoot(view);
    }
    if(data.id==="edx:falling_block_ground_dont_break" && entity ){
        const block = entity.dimension.getBlock(entity.location)
        if(block.isAir)
          block.setType(entity.typeId)
        else
          entity.dimension.spawnItem(new ItemStack(entity.typeId, 1), block.center());
      entity.remove()
    }
    if(data.id==="edx:falling_block_ground_break" && entity ){
      entity.dimension.playSound('break.suspicious_gravel',entity.location)
      entity.remove()
    }
    if(data.id==="edx:sus_item" && entity ){
        noBrushTest(entity)
    }
    if(data.id==="edx:true_wither" && entity ){
        entity.dimension.spawnEntity("edx:true_wither",location);
        entity.remove()
    }
    if(data.id==="edx:true_wither_fail" && entity ){ 
        entity.runCommand(`tellraw @a[r=50] { "rawtext": [ { "translate": "message.event.true_wither_before_dragon" } ] }`)
        entity.runCommand(`give @p[r=30] skull 3 1`)
        entity.runCommand(`give @p[r=30] soul_sand 4`)
        entity.remove()
    }
    if(data.id==="edx:gloopine_jump" && entity ){
      const power = Math.sqrt(entity.getViewDirection().x ** 2 + entity.getViewDirection().z ** 2)*2
        entity.applyKnockback({x:entity.getViewDirection().x*power,z: entity.getViewDirection().z*power}, 1)
        entity.setRotation({x:Math.random()*360,y:Math.random()*360})
    } 
    if(data.id==="edx:gloop_ball_jump" && entity ){
      const power = Math.sqrt(entity.getViewDirection().x ** 2 + entity.getViewDirection().z ** 2)*2
      entity.applyKnockback({x:entity.getViewDirection().x*power,z: entity.getViewDirection().z*power}, 1)
      entity.setRotation({x:Math.random()*360,y:Math.random()*360})
  } 
   
    if(data.id==="edx:magmroll_jump" && entity ){
      const power = Math.sqrt(entity.getViewDirection().x ** 2 + entity.getViewDirection().z ** 2)*4.5
      entity.applyKnockback({x:entity.getViewDirection().x*power,z: entity.getViewDirection().z*power}, 0.6)
    }
    if(data.id==="edx:skeleton_piranha" && entity){
      const power =  Math.sqrt(entity.getViewDirection().x ** 2 + entity.getViewDirection().z ** 2)*4.5
      entity.applyKnockback({x:entity.getViewDirection().x*power,z: entity.getViewDirection().z*power}, 4.2)
    }
    if(data.id==="edx:incendiary_throwing_potion" && entity){
      var entities = world.getDimension("Nether").getEntities({
        location: { x: entity.location.x, y: entity.location.y, z: entity.location.z },
        maxDistance: 2,
      });
      for (let entity of entities) {
        entity.setOnFire(10);
      }  
    }
    //blazeblade
    if(data.id==="edx:blazeblade_sun" && entity){
      entity.dimension.playSound('mob.blazeblade.sun',entity.location,{volume: 4.0,});
      var players = entity.dimension.getPlayers({
        location: { x: entity.location.x, y: entity.location.y, z: entity.location.z },
        maxDistance: 5,
      });
    for (let player of players) {
        if (player.hasTag("easy") ) {
            player.setOnFire(3, false);
            player.applyKnockback({x:0,z:0},1);
            player.applyDamage(8,{
                cause: "fire" ,
            },)
        }
        else if (player.hasTag("normal") ) {
            player.setOnFire(5, false);
            player.applyKnockback({x:0,z:0},1);
            player.applyDamage(14,{
                cause: "fire" ,
            },)
        }
        else if (player.hasTag("hard") ) {
            player.setOnFire(7, false);
            player.applyKnockback({x:0,z:0},1);
            player.applyDamage(20,{
                cause: "fire" ,
            })
        }
     }
    }
    if(data.id==="edx:blazeblade_solar_flare" && entity){//need to change
      entity.dimension.playSound('mob.blazeblade.solar_wave',entity.location,{volume: 3.0,});
      var players = entity.dimension.getPlayers({
        location: { x: entity.location.x, y: entity.location.y, z: entity.location.z },
        maxDistance: 64,
      });
      for (let player of players) {
        player.setOnFire(1, false);
      }
    }
    if(data.id==="edx:blazeblade_dig" && entity){
      entity.dimension.playSound('mob.blazeblade.dig_out',entity.location,{volume: 3.0,});
      var players = entity.dimension.getPlayers({
        location: { x: entity.location.x, y: entity.location.y, z: entity.location.z },
        maxDistance: 1.5,
      });
      for (let player of players) {
          if (player.hasTag("easy") ) {
              player.setOnFire(6, false);
              player.applyKnockback({x:0,z:0},1);
              player.applyDamage(8,{
                  cause: "fire" , 
              },)
          }
          else if (player.hasTag("normal") ) {
              player.setOnFire(8, false);
              player.applyKnockback({x:0,z:0},1);
              player.applyDamage(10,{
                  cause: "fire" ,
              },)
          }
          else if (player.hasTag("hard") ) {
              player.setOnFire(10, false);
              player.applyKnockback({x:0,z:0},1);
              player.applyDamage(12,{
                  cause: "fire" ,
              })
          }
      }
    }
    if(data.id==="edx:blazeblade_dash_1" && entity){
        var direction=entity.getViewDirection()
        entity.applyImpulse({ x:direction.x*4 , y: direction.y, z: direction.z*4 }) 
        entity.dimension.playSound('mob.blazeblade.dash',entity.location,{volume: 3.0,});
    }
    if(data.id==="edx:blazeblade_dash_2" && entity){
      var direction=entity.getViewDirection()
      entity.applyImpulse({ x:direction.x*6 , y: direction.y, z: direction.z*6 }) 
      entity.dimension.playSound('mob.blazeblade.dash',entity.location,{volume: 3.0,});
  }
  if(data.id==="edx:soul_blazeblade_dash_1" && entity){ 
    var direction=entity.getViewDirection()
    entity.applyImpulse({ x:direction.x*7 , y: direction.y, z: direction.z*8 }) 
    entity.dimension.playSound('mob.blazeblade.dash',entity.location,{volume: 4.0,});
}
if(data.id==="edx:soul_laser_prevent_x1" && entity){
  var direction=entity.getViewDirection()
  entity.applyImpulse({ x:1 , y: 0, z:0 })
  entity.dimension.playSound('mob.blazeblade.dash',entity.location,{volume: 4.0,});
}
if(data.id==="edx:soul_laser_prevent_x-" && entity){
  var direction=entity.getViewDirection()
  entity.applyImpulse({ x:-1 , y: 0, z:0 })
  entity.dimension.playSound('mob.blazeblade.dash',entity.location,{volume: 4.0,});
}
if(data.id==="edx:soul_laser_prevent_z1" && entity){
  var direction=entity.getViewDirection()
  entity.applyImpulse({ x:0 , y: 0, z:1 })
  entity.dimension.playSound('mob.blazeblade.dash',entity.location,{volume: 4.0,});
}
if(data.id==="edx:soul_laser_prevent_z-" && entity){
  var direction=entity.getViewDirection()
  entity.applyImpulse({ x:0 , y: 0, z:-1 })
  entity.dimension.playSound('mob.blazeblade.dash',entity.location,{volume: 4.0,});
} 
if(data.id==="edx:soul_ground_attack" && entity){
  var randomlocationx = Math.round(Math.random()*15)+1;
  var randomlocationx2 = Math.round(Math.random()*15)+1;
  var randomlocationz = Math.round(Math.random()*15)+1;
  var randomlocationz2 = Math.round(Math.random()*15)+1;
  var randomlocation_x = Math.round(Math.random()*-15)-1;
  var randomlocation_x2 = Math.round(Math.random()*-15)-1;
  var randomlocation_z = Math.round(Math.random()*-15)-1;
  var randomlocation_z2 = Math.round(Math.random()*-15)-1;
  entity.dimension.spawnEntity("edx:soul_ground_tornado",{ x: Math.round(entity.location.x)+randomlocationx, y: entity.location.y, z: entity.location.z+randomlocationz });
  entity.dimension.spawnEntity("edx:soul_ground_tornado",{ x: Math.round(entity.location.x)+randomlocationx2, y: entity.location.y, z: entity.location.z+randomlocation_z });
  entity.dimension.spawnEntity("edx:soul_ground_tornado",{ x: Math.round(entity.location.x)+randomlocation_x, y: entity.location.y, z: entity.location.z+randomlocationz2 });
  entity.dimension.spawnEntity("edx:soul_ground_tornado",{ x: Math.round(entity.location.x)+randomlocation_x2, y: entity.location.y, z: entity.location.z+randomlocation_z2 });
}
if(data.id==="edx:soul_laser_prevent_x2" && entity){
  var direction=entity.getViewDirection()
  entity.applyImpulse({ x:1 , y: 0, z:1 })
  entity.dimension.playSound('mob.blazeblade.dash',entity.location,{volume: 4.0,});
}
if(data.id==="edx:soul_laser_prevent_x2-" && entity){
  var direction=entity.getViewDirection()
  entity.applyImpulse({ x:-1 , y: 0, z:1 })
  entity.dimension.playSound('mob.blazeblade.dash',entity.location,{volume: 4.0,});
}
if(data.id==="edx:soul_laser_prevent_z2" && entity){
  var direction=entity.getViewDirection() 
  entity.applyImpulse({ x:1 , y: 0, z:-1 })
  entity.dimension.playSound('mob.blazeblade.dash',entity.location,{volume: 4.0,});
}
if(data.id==="edx:soul_laser_prevent_z2-" && entity){
  var direction=entity.getViewDirection()
  entity.applyImpulse({ x:-1 , y: 0, z:-1 })
  entity.dimension.playSound('mob.blazeblade.dash',entity.location,{volume: 4.0,});
}
    if(data.id==="edx:soul_blazeblade_dig" && entity){
      entity.dimension.playSound('mob.blazeblade.dig_out',entity.location,{volume: 3.0,});
      var players = entity.dimension.getPlayers({
        location: { x: entity.location.x, y: entity.location.y, z: entity.location.z },
        maxDistance: 1.5,
      });
      for (let player of players) {
          if (player.hasTag("easy") ) {
              player.setOnFire(8, false);
              player.applyKnockback(0,0,0,1);
              player.applyDamage(10,{
                  cause: "fire" ,
              },)
          }
          else if (player.hasTag("normal") ) {
              player.setOnFire(10, false);
              player.applyKnockback(0,0,0,1);
              player.applyDamage(12,{
                  cause: "fire" ,
              },)
          }
          else if (player.hasTag("hard") ) {
              player.setOnFire(12, false);
              player.applyKnockback(0,0,0,2);
              player.applyDamage(14,{
                  cause: "fire" ,
              })
          }
      }
    }
    if(data.id==="edx:soul_dash_particle" && entity){
    const vmap = new MolangVariableMap();
    vmap.setVector3('variable.direction', entity.getViewDirection());
   entity.dimension.spawnParticle('edx:soul_fire_breath',{x:entity.getHeadLocation().x+entity.getViewDirection().x/4,y:entity.getHeadLocation().y+entity.getViewDirection().y/4,z:entity.getHeadLocation().z+entity.getViewDirection().z/4},vmap);
}
});

function distance(vector1, vector2) {
  return Math.sqrt(Math.abs(vector1.x - vector2.x)**2 + Math.abs(vector1.y - vector2.y)**2 + Math.abs(vector1.z - vector2.z)**2)
}

function BlazebladeFireLine(entity,target)
{
  const dist = distance(entity.location,target.getHeadLocation())
  var line = Line(entity.getHeadLocation(), {x:target.location.x,y:target.location.y+1,z:target.location.z}, 0.9,dist)
  try{
    for (let loc of line) {
      entity.dimension.spawnParticle('edx:blazeblade_small_flame', loc)
    }
  }
  catch(e){}
}


function Line(vector1, vector2, step2 = 1,dist) {
  let step = {
    x: (vector2.x - vector1.x) / (dist || 1),
    y: (vector2.y - vector1.y) / (dist || 1),
    z: (vector2.z - vector1.z) / (dist || 1)
  }
  let list = []
  for (let i = step2; i < dist-step2; i += step2) {
    list.push({
      x: vector1.x + i*step.x,
      y: vector1.y + i*step.y,
      z: vector1.z + i*step.z
    })
  }
  return list
}