import {world, system, ItemStack} from '@minecraft/server';
import {spawnEnt, lc, durabilidad, dispararP} from './main.js';

system.beforeEvents.startup.subscribe(customC => {
  customC.blockComponentRegistry.registerCustomComponent('parasitesap:caer', {
    onEntityFallOn: boca => {
      const gs = boca.block;
      const ent = boca.entity;
      const ob = gs.permutation.getState('parasitesap:dientes')
      if (ob <= 0) return;
      const est = gs.permutation.withState("parasitesap:pisar", true);
      gs.setPermutation(est);
      if (!ent.typeId.includes('parasitesap:') && ent.typeId !== 'minecraft:xp_orb' && ent.typeId !== 'minecraft:item') ent.applyDamage(1);
    },
  });
  customC.blockComponentRegistry.registerCustomComponent('parasitesap:pisar', {
    onStepOn: boca => {
      const gs = boca.block;
      const ent = boca.entity;
      const ob = gs.permutation.getState('parasitesap:dientes')
      if (ob <= 0) return;
      const est = gs.permutation.withState("parasitesap:pisar", true);
      gs.setPermutation(est);
      if (!ent.typeId.includes('parasitesap:') && ent.typeId !== 'minecraft:xp_orb' && ent.typeId !== 'minecraft:item') ent.applyDamage(1);
    },
  });
  customC.blockComponentRegistry.registerCustomComponent('parasitesap:dejar_de_pisar', {
    onStepOff: boca => {
      const gs = boca.block;
      const est = gs.permutation.withState("parasitesap:pisar", false);
      gs.setPermutation(est);
    },
  });
  customC.blockComponentRegistry.registerCustomComponent('parasitesap:pisando', {
    onTick: boca => {
      const gs = boca.block;
      const ob = gs.permutation.getState('parasitesap:dientes')
      if (ob <= 0) {
        const kxhs = gs.permutation.withState("parasitesap:pisar", false);
        gs.setPermutation(kxhs);
      }
      const entity = gs.dimension.getEntities({location:{ x: gs.location.x, y: gs.location.y, z: gs.location.z},  maxDistance: 1.1});
      for (const ent of entity) {
        if (!ent.typeId.includes('parasitesap:') && ent.typeId !== 'minecraft:xp_orb' && ent.typeId !== 'minecraft:item') ent.applyDamage(1);
      }
    },
  });
//
  customC.blockComponentRegistry.registerCustomComponent("parasitesap:int", {
    onPlayerInteract: dientes => {
      const bloque = dientes.block;
      const ge = dientes.player;
      let item = ge.getComponent('inventory').container;
      const ob = bloque.permutation.getState('parasitesap:dientes');
      if (item.getItem(ge.selectedSlotIndex)?.typeId == 'minecraft:shears') {
        if (ob === 4) {
          bloque.dimension.spawnItem(new ItemStack('parasitesap:oth_b'), {x: bloque.location.x, y: bloque.location.y + 1, z: bloque.location.z});
          const est = bloque.permutation.withState("parasitesap:dientes", 3);
          bloque.setPermutation(est);
        }
        if (ob === 3) {
          bloque.dimension.spawnItem(new ItemStack('parasitesap:oth_b'), {x: bloque.location.x, y: bloque.location.y + 1, z: bloque.location.z});
          const est = bloque.permutation.withState("parasitesap:dientes", 2);
          bloque.setPermutation(est);
        }
        if (ob === 2) {
          bloque.dimension.spawnItem(new ItemStack('parasitesap:oth_b'), {x: bloque.location.x, y: bloque.location.y + 1, z: bloque.location.z});
          const est = bloque.permutation.withState("parasitesap:dientes", 1);
          bloque.setPermutation(est);
        }
        if (ob === 1) {
          bloque.dimension.spawnItem(new ItemStack('parasitesap:oth_b'), {x: bloque.location.x, y: bloque.location.y + 1, z: bloque.location.z});
          const est = bloque.permutation.withState("parasitesap:dientes", 0);
          bloque.setPermutation(est);
        }
        if (ob > 0 && !ge.matches({gameMode: "creative"})) {
          const sl = item.getItem(ge.selectedSlotIndex);
          const o = 1;
          durabilidad(ge, sl, o);
        }
      }
      if (item.getItem(ge.selectedSlotIndex)?.typeId == 'parasitesap:oth_b') {
        const kxhs = bloque.permutation.withState("parasitesap:pisar", false);
        if (ob < 4 && !ge.matches({gameMode: "creative"})) {
          ge.runCommand('clear @s parasitesap:oth_b 0 1');
        }
        if (ob === 3) {
          const est = bloque.permutation.withState("parasitesap:dientes", 4);
          bloque.setPermutation(kxhs);
          bloque.setPermutation(est);
        }
        if (ob === 2) {
          const est = bloque.permutation.withState("parasitesap:dientes", 3);
          bloque.setPermutation(kxhs);
          bloque.setPermutation(est);
        }
        if (ob === 1) {
          const est = bloque.permutation.withState("parasitesap:dientes", 2);
          bloque.setPermutation(kxhs);
          bloque.setPermutation(est);
        }
        if (ob === 0) {
          const est = bloque.permutation.withState("parasitesap:dientes", 1);
          bloque.setPermutation(est);
        }
      }
    },
  });
  customC.blockComponentRegistry.registerCustomComponent('parasitesap:infectar_bloques', {
    onTick: ma => {
      try {
        const block = ma.block;
        const dim = world.getDimension(block.dimension.id);
        const hasEntity = dim.getEntities({ families: ["spiowwjdixj"] }).length > 0;
        if (!hasEntity) {
          const replacements = {
            dirt: "minecraft:dirt",
            stone: dim.id === "minecraft:overworld" ? "minecraft:cobblestone" : dim.id === "minecraft:nether" ? "minecraft:netherrack" : dim.id === "minecraft:the_end" ? "minecraft:end_stone" : "minecraft:cobblestone",
            trunk: "minecraft:oak_wood",
            planks: "minecraft:oak_planks"
          };
          for (const [key, value] of Object.entries(replacements)) {
            if (block.typeId.includes(key)) {
              block.setType(value);
              return;
            }
          }
          return;
        }
        const directions = [
          { dx: 0, dy: 1, dz: 0 },
          { dx: 0, dy: -1, dz: 0 },
          { dx: 1, dy: 0, dz: 0 },
          { dx: -1, dy: 0, dz: 0 },
          { dx: 0, dy: 0, dz: 1 },
          { dx: 0, dy: 0, dz: -1 }
        ];
        const infectionM = {
          dirt: "parasitesap:infected_dirt",
          grass: "parasitesap:infected_dirt",
          sand: "parasitesap:infected_dirt",
          stone: "parasitesap:infested_stone",
          deepslate: "parasitesap:infested_stone",
          netherrack: "parasitesap:infested_stone",
          log: "parasitesap:infected_trunk",
          wood: "parasitesap:infected_planks",
          planks: "parasitesap:infected_planks"
        };
        for (const { dx, dy, dz } of directions) {
          const neighborBlock = dim.getBlock({
            x: block.location.x + dx,
            y: block.location.y + dy,
            z: block.location.z + dz
          });
          for (const [key, value] of Object.entries(infectionM)) {
            if (neighborBlock.typeId.includes(key) && !neighborBlock.typeId.startsWith("parasitesap:") ||
neighborBlock.hasTag(key)) {
               neighborBlock.setType(value);
              break;
            }
          }
        }
      } catch (error) {} finally{}
    },
  });
  customC.blockComponentRegistry.registerCustomComponent('parasitesap:piso', {
    onTick: ma => {
      const blo = ma.block;
      blo.setType('minecraft:air');
    },
  });
  customC.blockComponentRegistry.registerCustomComponent("parasitesap:grass", {
    onRandomTick: cb => {
      const blo = cb.block;
      const loc = blo.dimension.getBlock({x: blo.location.x, y: blo.location.y + 1, z: blo.location.z});
      if (!loc.isAir) {
        const est = blo.permutation.withState('parasitesap:pi', false);
        blo.setPermutation(est)
      }
      else {
        function pasto0(p) {
          const est = p.permutation.withState('parasitesap:pi', false);
          p.setPermutation(est);
        }
        function pasto1(p) {
          const randomBlocks = ["parasitesap:pg", "parasitesap:pgg"];
          p.above(1).setType(randomBlocks[Math.floor(Math.random()*randomBlocks.length)]);
          const est = p.permutation.withState('parasitesap:pi', false);
          p.setPermutation(est);
        }
        const sr = [pasto0, pasto1];
        const sb = Math.floor(Math.random() * sr.length);
        sr[sb](blo);
      }
    },
  });
//
  customC.itemComponentRegistry.registerCustomComponent("parasitesap:t", {
    onHitEntity: hit => {
      const gs = hit.hitEntity
      const tileEntity = world
      .getDimension(gs.dimension.id)
      .getEntities({ type: "parasitesap:booster" })[0];
      if (gs.typeId.includes('parasitesap:') || gs.typeId === 'minecraft:player') return;
      spawnEnt(gs, tileEntity);
      lc(gs);
      return;
    },
  });
  customC.itemComponentRegistry.registerCustomComponent("parasitesap:phase_indicator", {
    onUse: p => {
      const item = p.source
      const dim = world.getDimension(item.dimension.id).id;
      const sc = world.scoreboard.getObjective("parasitephasegs").getScore(`parasitesaphase_${dim}_num`);
      item.onScreenDisplay.setActionBar(`${sc}`);
      //item.onScreenDisplay.setActionBar(`${sc}\n§7dimension: §f${dim}`);
    },
  });
  customC.itemComponentRegistry.registerCustomComponent("parasitesap:b", {
    onUse: b => {
      const ballesta = "parasitic_crossbow"
      const item = b.source;
      const inventory = item.getComponent("minecraft:inventory").container;
      let at = false;
      function ggg() {
        at = true;
        item.playSound('crossbow.loading.start', {location: item.location});
      }
      for (let i = 0; i < inventory.size; i++) {
        const flecha = inventory.getItem(i);
        const offHand = item.getComponent("minecraft:equippable").getEquipmentSlot(`Offhand`).getItem();
        if (flecha?.typeId === "minecraft:arrow" && at === false) ggg();
        else if (offHand?.typeId === 'minecraft:arrow' && at == false) ggg();
        else if (item.matches({gameMode: 'creative'}) && at === false) ggg();
      }
    },
    onCompleteUse: b => {
      const ballesta = "parasitic_crossbow"
      const item2 = b.itemStack;
      const source = b.source;
      const nombre = item2.nameTag;
      let c = item2.getComponent('minecraft:durability').damage;
      const inventory = source.getComponent("minecraft:inventory").container;
      let at = false;
      const enchantment = item2.getComponent("enchantable")?.getEnchantments();
      function cargar() {
        at = true;
        if (!source.matches({gameMode: 'creative'})) source.runCommand(`clear @s arrow -1 1`);
        source.playSound('crossbow.loading.middle', {location: source.location});
        system.runTimeout(()=>{
          source.playSound('crossbow.quick_charge.middle', {location: source.location});
        }, 12);
        const item = new ItemStack("parasitesap:parasitic_crossbow_charged", 1);
        let durability = item.getComponent("minecraft:durability");
        
        if (enchantment) item.getComponent('enchantable')?.addEnchantments(enchantment);
        if (source.matches({gameMode: 'creative'})) {
          durability.damage = c;
          item.setLore([`§7${durability.maxDurability - durability.damage}/${durability.maxDurability}`]);
          item.nameTag = nombre;
          source.getComponent('inventory').container.setItem(source.selectedSlotIndex, item);
        }
        else if (!source.matches({gameMode: 'creative'})) {
          const durabi = item2?.getComponent("durability");
          const lvl = item2?.getComponent('enchantable').getEnchantment('unbreaking')?.level ?? 0;
          const breakingP = 100 / (lvl + 1);
          const breakingR = (Math.random() * 100);
          if (breakingP < breakingR) {
            durability.damage = c;
            item.setLore([`§7${durability.maxDurability - durability.damage}/${durability.maxDurability}`]);
            item.nameTag = nombre;
            source.getComponent('inventory').container.setItem(source.selectedSlotIndex, item);
            return;
          }
          else if (durabi.damage < durabi.maxDurability) {
            durability.damage = c+1;
          }
          else if (durabi.damage >= durabi.maxDurability) {
            source.getComponent('inventory').container.setItem(source.selectedSlotIndex, new ItemStack('minecraft:air'));
            source.playSound('random.break', source.location);
            return;
          }
          item.setLore([`§7${durability.maxDurability - durability.damage}/${durability.maxDurability}`]);
          item.nameTag = nombre;
          source.getComponent('inventory').container.setItem(source.selectedSlotIndex, item);
        }
      }
      for (let i = 0; i < inventory.size; i++) {
        const flecha = inventory.getItem(i);
        const offHand = source.getComponent("minecraft:equippable").getEquipmentSlot(`Offhand`).getItem();
        if (flecha?.typeId === "minecraft:arrow" && at === false) cargar();
        else if (offHand?.typeId === 'minecraft:arrow' && at === false) cargar();
        else if (source.matches({gameMode: 'creative'}) && at === false) cargar();
      }
    },
  });
  customC.itemComponentRegistry.registerCustomComponent("parasitesap:b_g", {
    onCompleteUse: g => {
      /*try {
        world.scoreboard.addObjective("flecha_parasitesap", "flecha_parasitesap");
      } catch (error){} finally{}*/
      const ballesta = "parasitic_crossbow_charged"
      const sisj = g.itemStack;
      const source = g.source;
      const encantamientos = sisj.getComponent('enchantable').getEnchantments();
      const nombre = sisj.nameTag;
      const c =sisj.getComponent('minecraft:durability').damage;
      dispararP(source, 'parasitesap:flecha', 8)
      //
      const multi = sisj.getComponent("enchantable")?.getEnchantment('multishot') ?? 0;
      const enchantment = sisj.getComponent("enchantable")?.getEnchantments();
      //
      if (multi !=0) {
        const sourceRot = source.getRotation();
        //
        const sp1 = source.dimension.spawnEntity('parasitesap:flecha', source.getHeadLocation());
        sp1.addTag('parasitesap:remover');
        const component1 = sp1.getComponent('minecraft:projectile');
        sp1.setRotation({x: sourceRot.x, y: sourceRot.y - 9.5})
        const view1 = sp1.getViewDirection();
        component1.owner = source;
        component1.shoot({x: view1.x*8, y: view1.y*8, z: view1.z*8});
        //
        const sp2 = source.dimension.spawnEntity('parasitesap:flecha', source.getHeadLocation());
        sp2.addTag('parasitesap:remover');
        const component2 = sp2.getComponent('minecraft:projectile');
        sp2.setRotation({x: sourceRot.x, y: sourceRot.y + 9.5});
        const view2 = sp2.getViewDirection();
        component2.owner = source;
        component2.shoot({x: view2.x*8, y: view2.y*8, z: view2.z*8});
        //
      }
      source.playSound('crossbow.shoot', {location: source.location});
      const item = new ItemStack('parasitesap:parasitic_crossbow', 1);
      //
      if (enchantment) item.getComponent('enchantable')?.addEnchantments(enchantment)
      //
      let durability = item.getComponent("minecraft:durability");
      durability.damage = c;
      item.nameTag = nombre;
      item.setLore([`§7${durability.maxDurability - durability.damage}/${durability.maxDurability}`]);
      source.getComponent('minecraft:inventory').container.setItem(source.selectedSlotIndex, item);
    },
  });
});