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

const fenceTags = ["custom_fence", "sword_mine", "axe_mine", "pickaxe_mine", "shovel_mine", "hoe_mine", "metal", "wood", "stone", "wood_pick_diggable", "stone_pick_diggable", "iron_pick_diggable", "gold_pick_diggable", "diamond_pick_diggable", "netherite_pick_diggable", "dirt", "sand", "gravel", "grass", "snow"];

world.beforeEvents.worldInitialize.subscribe(initEvent => {

  initEvent.blockComponentRegistry.registerCustomComponent('we:fence_place', {
    onPlace: e => {
      const newPermutation = e.block.permutation.withState('we:placed_bit', 1);

      e.block.setPermutation(newPermutation);
    }
  });
  initEvent.blockComponentRegistry.registerCustomComponent('we:fence_tick', {
    onTick: e => {
      const block = e.block;
      const north = block.north();
      const south = block.south();
      const east = block.east();
      const west = block.west();
      const permutation = block.permutation;

      var northPerm = false;
      var southPerm = false;
      var westPerm = false;
      var eastPerm = false;

      if (north.isAir === false) {
        const northTags = north.getTags();

        for (const tag of northTags) {
          if (fenceTags.includes(tag)) {
            northPerm = true;
            break;
          }
        }
      }
      if (!south.isAir) {
        const southTags = south.getTags();

        for (const tag of southTags) {
          if (fenceTags.includes(tag)) {
            southPerm = true;
            break;
          }
        }
      }
      if (!east.isAir) {
        const eastTags = east.getTags();

        for (const tag of eastTags) {
          if (fenceTags.includes(tag)) {
            eastPerm = true;
            break;
          }
        }
      }
      if (!west.isAir) {
        const westTags = west.getTags();

        for (const tag of westTags) {
          if (fenceTags.includes(tag)) {
            westPerm = true;
            break;
          }
        }
      }

      const currentStates = permutation.getAllStates();

      const newStates = {
        ...currentStates,
        'we:north': northPerm,
        'we:south': southPerm,
        'we:east': eastPerm,
        'we:west': westPerm
      };
      const newPermutation = BlockPermutation.resolve(block.typeId, newStates);
      block.setPermutation(newPermutation);
    }
  });
});