import { getDirectionVector, getDistance, OVERWORLD, SOUND_OPTIONS } from "./main";
import { BlockVolume, world, system } from "@minecraft/server"
/**
 *
 * @param {keyof typeof SOUNDS} noiseNameInput
 * @param {Vector3} sourceLocation
 * @param {number} range
 * @param {number} initialVolume
 */
export function broadcastNoise(noiseNameInput, sourceLocation, range, initialVolume) {
    const receivedEntities = OVERWORLD.getEntities({ location: sourceLocation, maxDistance: range });
  
    for (let entity of receivedEntities) {
      if (entity.typeId !== "js:eyeless_dog" && entity.typeId !== "js:company") continue;
  
      const distance = getDistance(entity.location, sourceLocation);
  
      const volume = Math.max(0, initialVolume * (1 - 0.5 * (distance / range)));
  
      if (entity.typeId == "js:company") {
        if (
          (noiseNameInput == "bell" || volume > 0.4) &&
          noiseNameInput !== "drop_scrap" &&
          noiseNameInput !== "dropship" &&
          noiseNameInput !== "sprint" &&
          noiseNameInput !== "walk" &&
          noiseNameInput !== "fall"
        ) {
          const playerCount = world.getAllPlayers().length;
          let subtractedValue = 2;
          subtractedValue = Math.round((subtractedValue * volume) / playerCount);
  
          //  console.warn(`Subtract ${subtractedValue}`)
  
          if (entity.doorTimer > 0) {
            entity.doorTimer -= subtractedValue;
          }
          /*
                  if (entity.doorTimer < 0) {
                      entity.doorTimer = 0
                  }
                  */
          const patienceSubtractAmount = 0.4 * volume * entity.irritability;
          if (entity.patienceCooldown == 0) {
            entity.patienceSubtractAmount = patienceSubtractAmount;
            //  console.warn(`adding patience of ${entity.patienceSubtractAmount}`)
          }
          entity.patienceCooldown++;
          if (entity.patienceCooldown > 0) {
            //    console.warn(`cooling down`)
            system.runTimeout(() => {
              entity.patienceCooldown = 0;
              //     console.warn(`cooled down`)
            }, 20);
          }
  
          if (entity.attack == 0 && entity.patience < 1) {
            const chance = Math.random();
            if (chance < 0.5) {
              entity.attack = 1;
            }
          }
          if (entity.patience <= 1.5) {
            OVERWORLD.playSound("monster.company.angry", entity.location, SOUND_OPTIONS);
            OVERWORLD.playSound("monster.company.wall_rumble", entity.location, SOUND_OPTIONS);
            entity.runCommand(`camerashake add @a[r=12] 0.5 1.2 rotational`);
          }
        }
      }
      if (entity.typeId == "js:eyeless_dog") {
        const entityLocation = entity.getHeadLocation();
        const directionVector = getDirectionVector(entityLocation, sourceLocation);
        // console.warn(JSON.stringify(directionVector))
        let suspicion = /** @type {number} */ (entity.getProperty("js:suspicion"));
        const state = /** @type {number} */ (entity.getProperty("js:state"));
  
        let noiseLoundess = volume;
        const lineOfSightCheck = OVERWORLD.getBlockFromRay(entityLocation, directionVector, { maxDistance: 28 });
        if (!lineOfSightCheck) {
          noiseLoundess = volume / 2;
        }
  
        const distance = getDistance(entityLocation, sourceLocation);
        //  console.warn(`Dist ${distance} Loud ${(18 * noiseLoundess)}`)
        if (distance < 18 * noiseLoundess) {
          const vol = new BlockVolume(sourceLocation, {
            x: sourceLocation.x,
            y: sourceLocation.y + 1,
            z: sourceLocation.z,
          });
          OVERWORLD.fillBlocks(vol, "js:sound_marker", { blockFilter: { includeTypes: [`minecraft:air`] } });
  
          if (state < 3) {
            entity.setProperty("js:suspicion", 11);
          }
        }
  
        const isSaddled = entity.hasComponent("minecraft:is_saddled");
        const isIllagerCaptain = entity.hasComponent("minecraft:is_illager_captain");
  
        if (isIllagerCaptain == false && noiseLoundess > 0.25 && entity.growlCooldown == 0) {
          const vol = new BlockVolume(sourceLocation, {
            x: sourceLocation.x,
            y: sourceLocation.y + 1,
            z: sourceLocation.z,
          });
          OVERWORLD.fillBlocks(vol, "js:sound_marker", { blockFilter: { includeTypes: [`minecraft:air`] } });
  
          entity.setProperty("js:suspicion", suspicion <= 10 ? suspicion + 1 : 11);
  
          if (entity.growl == 0 && entity.growlCooldown == 0) {
            entity.growl = 1;
          }
  
          if (state == 3 && !isSaddled) {
            entity.triggerEvent("investigate_angry");
          }
        }
      }
    }
  }