import { COMPANY_MOODS, ITEM_LIST } from "./data";
import { creditsScoreboard, OVERWORLD, SOUND_OPTIONS, worldPlayers } from "./main";
import { world, system, EntityDamageCause } from "@minecraft/server"
import { updateProfitDisplay } from "./terminal";

import { damagePlayer } from "./initialize";

/**
 * @param {Entity} entity
 */
export function companyRuntime(entity) {
    let companyMood = world.getDynamicProperty("companyMood");
    if (typeof companyMood !== "string") {
      world.setDynamicProperty("companyMood", "agitated");
      companyMood = "agitated";
    }
    // @ts-ignore
    entity.mood = companyMood;
    entity.doorTimer = 31;
    entity.interval = 0;
    entity.patienceSubtractAmount = 0;
    entity.patienceCooldown = 0;
    entity.attack = 0;
    entity.kills = 0;
  
    entity.patience = COMPANY_MOODS[entity.mood].starting_patience;
    entity.irritability = COMPANY_MOODS[entity.mood].irritability;
    entity.sensitivity = COMPANY_MOODS[entity.mood].sensitivity;
    entity.maxKills = COMPANY_MOODS[entity.mood].max_player_kills;
    entity.judgementSpeed = COMPANY_MOODS[entity.mood].judgement_speed;
  
    const companyInterval = system.runInterval(() => {
      if (!entity) {
        system.clearRun(companyInterval);
        entity?.remove();
      }
      if (!entity.isValid) {
        system.clearRun(companyInterval);
      }
  
       //  entity.nameTag = (`attack ${entity.attack} timer ${entity.doorTimer} patience ${entity.patience}`)
  
      if (entity.attack == 0) {
            // console.warn(entity.interval)
            //  console.warn(`timer ${entity.doorTimer} patience ${entity.patience}`)
  
        entity.interval++;
        if (entity.patienceSubtractAmount > 0) {
          entity.patience -= entity.patienceSubtractAmount;
          entity.patienceSubtractAmount = 0;
        }
        if (entity.interval % 20 == 0) {
          if (entity.doorTimer < 31 && entity.doorTimer > -10) {
            entity.doorTimer--;
          }
          if (entity.doorTimer <= 0) {
            entity.setProperty("js:door", 1);
          }
          if (entity.doorTimer <= -10) {
            entity.doorTimer = 31;
            const scrapEntities = [
              ...OVERWORLD.getEntitiesAtBlockLocation({
                x: entity.location.x,
                y: entity.location.y,
                z: entity.location.z,
              }),
              ...OVERWORLD.getEntitiesAtBlockLocation({
                x: entity.location.x + 1,
                y: entity.location.y,
                z: entity.location.z,
              }),
              ...OVERWORLD.getEntitiesAtBlockLocation({
                x: entity.location.x - 1,
                y: entity.location.y,
                z: entity.location.z,
              }),
              ...OVERWORLD.getEntitiesAtBlockLocation({
                x: entity.location.x + 2,
                y: entity.location.y,
                z: entity.location.z,
              }),
            ];
  
            OVERWORLD.playSound("monster.company.take_items", entity.location, SOUND_OPTIONS);
  
            let totalValue = 0;
            let totalValueWithoutPercentage = 0;
            let numberOfScrapSold = 0;
            const scrapTeleportLocation = {
              x: entity.location.x - 0.5,
              y: entity.location.y,
              z: entity.location.z + 1.5,
            };
  
            let sellPercentage = 1;
            const day = /** @type {number} */ (world.getDynamicProperty("day")) ?? 0;
            if (day == 4) {
              sellPercentage = 0.3;
            } else if (day == 3) {
              sellPercentage = 0.53;
            } else if (day == 2) {
              sellPercentage = 0.77;
            } else if (day <= 1) {
              sellPercentage = 1;
            }
  
            /** @type {Record<string, { name?: string; count: number; totalValue: number }>} */
            const scrapSummary = {};
  
            for (let scrap of scrapEntities) {
              const typeId = scrap.typeId.split("_ent")[0];
              if (ITEM_LIST[typeId]) {
                scrap.teleport(scrapTeleportLocation);
  
                let value = /** @type {number} */ (scrap.getDynamicProperty("scrapValue")) ?? 0;
                let sellValue = Math.floor(value * sellPercentage);
                totalValue += sellValue;
                totalValueWithoutPercentage += value;
  
                if (!scrapSummary[typeId]) {
                  scrapSummary[typeId] = {
                    name: ITEM_LIST[typeId].name,
                    count: 0,
                    totalValue: 0,
                  };
                }
  
                scrapSummary[typeId].count++;
                scrapSummary[typeId].totalValue += sellValue;
  
                numberOfScrapSold++;
  
                system.runTimeout(() => {
                  scrap?.remove();
                }, 12);
              }
            }
  
            let totalValueStr = totalValue.toString().padStart(6, "0");
  
            let message = `dingUI:paycheck__${totalValueStr}`;
  
            for (let scrapType in scrapSummary) {
              const { name, count, totalValue } = scrapSummary[scrapType];
              message += `\n${name} (${count}x) : ${totalValue}`;
            }
  
            console.warn(totalValue);
            entity.playAnimation('animation.company.take_items')
  
            let judgementSpeed = entity.judgementSpeed;
            system.runTimeout(() => {
              let averageScrapValue = totalValueWithoutPercentage / numberOfScrapSold;
              let chance = Math.random() * 100;
              if (averageScrapValue <= 3 && entity.patience <= 2 && chance <= 30) {
                entity.attack = 1;
              } else {
                entity.setProperty("js:door", 0);
  
                entity.patience = entity.patience + 3;
  
                system.runTimeout(() => {
                  const currentCredits = creditsScoreboard.getScore("world");
                  if (totalValueWithoutPercentage < (currentCredits / 100) * 25) {
                    worldPlayers.forEach((player) => {
                      player.playSound('monster.company.reward_mid')
                      player.sendMessage(`${message}`);
                    })
                  } else {
                    worldPlayers.forEach((player) => {
                      player.playSound('monster.company.reward_good')
                      player.sendMessage(`${message}`);
                    })
                  }
  
                  creditsScoreboard.setScore("world", currentCredits + totalValue);
  
                  const scrapSold = world.getDynamicProperty("scrapSold");
                  world.setDynamicProperty("scrapSold", scrapSold + totalValue);
  
                  system.runTimeout(() => {
                    let soundChance = Math.random() * 100;
                    if (soundChance <= 3) {
                      OVERWORLD.playSound("monster.company.speaker_rare", entity.location, SOUND_OPTIONS);
                    } else {
                      OVERWORLD.playSound("monster.company.speaker_normal", entity.location, SOUND_OPTIONS);
                    }
                  }, 10);
  
                  system.run(() => {
                    updateProfitDisplay();
                  });
                }, 10);
              }
            }, judgementSpeed * 20);
          }
        }
  
        if (entity.interval % 100 == 0) {
          // if (entity.patienceSubtractAmount == 0) {
          //   entity.patience += 0.5;
          //   if (entity.patience > COMPANY_MOODS[entity.mood].starting_patience) {
          //     entity.patience = COMPANY_MOODS[entity.mood].starting_patience;
          //   }
          // }
          entity.interval = 0;
        }
      }
      if (entity.attack == 1) {
        if (entity.kills >= entity.maxKills) {
          entity.attack = 2;
        } else {
          entity.kills++;
          entity.setProperty("js:door", 1);
          entity.playAnimation('animation.company.attack')
          OVERWORLD.playSound("monster.company.attack", entity.location, SOUND_OPTIONS);
          OVERWORLD.playSound("monster.company.angry2", entity.location, SOUND_OPTIONS);
          OVERWORLD.playSound("monster.company.wall_rumble_voice", entity.location, SOUND_OPTIONS);
    
          const killed = OVERWORLD.getEntities({
            type: "minecraft:player",
            location: entity.location,
            closest: 1,
            maxDistance: 4,
          });
    
          damagePlayer(killed[0], 100, entity, EntityDamageCause.contact);
    
          entity.runCommand(`camerashake add @a[r=12] 0.8 2 rotational`);

        }
      }
      if (entity.attack == 2) {
        entity.attack = 0;
        system.runTimeout(() => {
          entity.setProperty("js:door", 0);
          entity.patience = entity.patience + 6;
        }, 2 * 20);
      }
    });
  }