import './durability';

import {
  world,
  ItemStack,
  Player,
  system,
  EntityInitializationCause,
} from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";

world.afterEvents.playerSpawn.subscribe(event => {
  const { player } = event;
  if (player.getDynamicProperty('compycraft_era:given_scroll')) return;
  player.dimension.spawnItem(new ItemStack('compycraft_era:guide_scroll'), player.location)
  player.setDynamicProperty('compycraft_era:given_scroll', true)
})

world.afterEvents.playerSpawn.subscribe((event) => {
  const { player } = event;
  if (player.getDynamicProperty("compycraft_era:given_book")) return;
  player.dimension.spawnItem(
    new ItemStack("compycraft_era:guide_book"),
    player.location
  );
  player.setDynamicProperty("compycraft_era:given_book", true);
});

world.afterEvents.itemUse.subscribe((event) => {
  const { itemStack, source } = event;
  if (itemStack.typeId != "compycraft_era:guide_book") return;
  const form = new ActionFormData()
    .title({ translate: "compycraft_era.guide_book.title" })
    .body({
      rawtext: [
        { translate: "compycraft_era.guide_book.text_1" },
        { text: "\n" },
        { text: "\n" },
        { translate: "compycraft_era.guide_book.text_2" },
        { text: "\n" },
        { text: "\n" },
      ],
    })
    .button({ translate: "compycraft_era.guide_book.exit" })
    .button({ translate: "§l§2Edit Global Settings!§r" });
  form.show(source).then((r) => {
    if (r.canceled) return;
    if (r.selection == 1) {
      GlobalMenuModal(source);
    }
  });
});

const dinosaurs = [
  "compycraft_era:acrocanthosaurus",
  "compycraft_era:allosaurus",
  "compycraft_era:amargasaurus",
  "compycraft_era:ankylosaurus",
  "compycraft_era:anomalocaris",
  "compycraft_era:archelon",
  "compycraft_era:argentinosaurus",
  "compycraft_era:arthropleura",
  "compycraft_era:baryonyx",
  "compycraft_era:brachiosaurus",
  "compycraft_era:campanile",
  "compycraft_era:camptosaurus",
  "compycraft_era:carnotaurus",
  "compycraft_era:ceratosaurus",
  "compycraft_era:compsognathus",
  "compycraft_era:deinocheirus",
  "compycraft_era:dunkleosteus",
  "compycraft_era:dilophosaurus",
  "compycraft_era:dimetrodon",
  "compycraft_era:dimorphodon",
  "compycraft_era:diplodocus",
  "compycraft_era:dryosaurus",
  "compycraft_era:edmontosaurus",
  "compycraft_era:elasmosaurus",
  "compycraft_era:facivermis",
  "compycraft_era:giganotosaurus",
  "compycraft_era:ichthyotitan",
  "compycraft_era:iguanodon",
  "compycraft_era:jaekelopterus",
  "compycraft_era:kaprosuchus",
  "compycraft_era:kentrosaurus",
  "compycraft_era:kumimanu",
  "compycraft_era:lambeosaurus",
  "compycraft_era:leedsichthys",
  "compycraft_era:liopleurodon",
  "compycraft_era:lythronax",
  "compycraft_era:maiasaura",
  "compycraft_era:mamenchisaurus",
  "compycraft_era:mammoth",
  "compycraft_era:microraptor",
  "compycraft_era:mosasaurus",
  "compycraft_era:nasutoceratops",
  "compycraft_era:ouranosaurus",
  "compycraft_era:oviraptor",
  "compycraft_era:pachycephalosaurus",
  "compycraft_era:parasaurolophus",
  "compycraft_era:protoceratops",
  "compycraft_era:psittacosaurus",
  "compycraft_era:pteranodon",
  "compycraft_era:quetzalcoatlus",
  "compycraft_era:saltasaurus",
  "compycraft_era:smilodon",
  "compycraft_era:spinosaurus",
  "compycraft_era:stegosaurus",
  "compycraft_era:therizinosaurus",
  "compycraft_era:triceratops",
  "compycraft_era:tupandactylus",
  "compycraft_era:tyrannosaurus",
  "compycraft_era:utahraptor",
  "compycraft_era:vasuki",
  "compycraft_era:velociraptor",
  "compycraft_era:xiphactinus",
  "compycraft_era:yutyrannus",
  "compycraft_era:vorombe",
  "compycraft_era:purussaurus",
  "compycraft_era:herrerasaurus",
  "compycraft_era:gigantopithecus",
  "compycraft_era:fasolasuchus",
  "compycraft_era:cryptoprocta",
  "compycraft_era:eagle",
  "compycraft_era:arizonasaurus",
  "compycraft_era:arctodus"
];

world.afterEvents.dataDrivenEntityTrigger.subscribe((data) => {
  const { eventId: event, entity } = data;
  if (dinosaurs.includes(entity.typeId)) {

    const player = entity?.dimension.getEntities({
      type: "minecraft:player",
      location: entity.location,
      tags: ["hasInt"],
      closest: 1,
      maxDistance: 7,
    })[0];
    if (event == "openMenu") {
      DinoMenu(player, entity);
      player.removeTag("hasInt");
    }
    if (event == "stand") {
      entity.setProperty("compycraft_era:sneak", false);
    }
    if (event == "sit") {
      entity.setProperty("compycraft_era:sneak", true);
    }
  }
});

world.afterEvents.entityHitEntity.subscribe((event) => {
  const {damagingEntity, hitEntity} = event
  if (damagingEntity instanceof Player){
    if (hitEntity.typeId == "compycraft_era:hit_mob"){
      const rideEntity = damagingEntity.getComponent("minecraft:riding")
      const ridingEntity = rideEntity.entityRidingOn
      if (ridingEntity){
        if(dinosaurs.includes(ridingEntity.typeId)){
          ridingEntity.playAnimation("attacking")
          ridingEntity.runCommand("execute positioned ^^^6 run damage @e[r=3] 10")
          ridingEntity.runCommand("execute positioned ^^^5 run damage @e[r=3] 10")
          ridingEntity.runCommand("execute positioned ^^^4 run damage @e[r=2] 10")
          ridingEntity.runCommand("execute positioned ^^^3 run damage @e[r=1] 10")
          ridingEntity.runCommand("execute positioned ^^^2 run damage @e[r=1] 10")
          //ridingEntity.runCommand("say estou attackando");
        }
      }
    }
  }
});

export function DinoMenu(player, dino) {
  const menu = new ActionFormData();
  menu.title("§2Dino Menu");
  menu.body("Select a command option!");
  if (
    dino.getComponent("minecraft:is_saddled") &&
    dino.getProperty("compycraft_era:sneak") == false
  ) {
    menu.button("Ride");
  }
  menu.button("Follow Owner");
  menu.button("Wander Around");
  menu.button("Stand Still");
  menu.button("§l§8Other Options");

  menu.show(player).then((r) => {
    if (r.canceled) return;
    if (
      dino.getComponent("minecraft:is_saddled") &&
      dino.getProperty("compycraft_era:sneak") == false
    ) {
      if (r.selection == 0) {
        player.runCommand("summon compycraft_era:hit_mob ^^1.5^2");
        dino.runCommand(`ride @e[name="${player.name}"] start_riding @s`);
      }
      if (r.selection == 1) {
        dino.triggerEvent("follow");
      }
      if (r.selection == 2) {
        dino.triggerEvent("unfollow");
      }
      if (r.selection == 3) {
        dino.triggerEvent("stand_still");
      }
      if (r.selection == 4) {
        DinoMenuModal(player, dino);
      }
    } else {
      if (r.selection == 0) {
        dino.triggerEvent("follow");
      }
      if (r.selection == 1) {
        dino.triggerEvent("unfollow");
      }
      if (r.selection == 2) {
        dino.triggerEvent("stand_still");
      }
      if (r.selection == 3) {
        DinoMenuModal(player, dino);
      }
    }
  });
}

export function DinoMenuModal(player, dino) {
  const menu = new ModalFormData();
  menu.title("§2Dinosaur Menu");

  if (
    dino.getComponent("minecraft:is_saddled")
  ) {
    menu.slider("Saddle Leather Colour", 0, 2, 1);
  }

  if (dino.getDynamicProperty("compycraft_era:hunt") == undefined) {
    dino.setDynamicProperty("compycraft_era:hunt", false);
  }

  menu.toggle("Hunt Mobs", dino.getDynamicProperty("compycraft_era:hunt"));
  if (dino.getDynamicProperty("compycraft_era:name") == undefined) {
    dino.setDynamicProperty("compycraft_era:name", "Type here!");
  }
  menu.textField(
    "Rename:",
    `${dino.getDynamicProperty("compycraft_era:name")}`
  );

  menu.show(player).then((r) => {
    if (r.canceled) return;

    if (r.formValues[0] != undefined) {
      dino.setProperty("compycraft_era:saddle", r.formValues[0]);
    }
    if (r.formValues[1] == true) {
      dino.triggerEvent("hunt");
      dino.setDynamicProperty("compycraft_era:hunt", true);
    } else {
      dino.triggerEvent("unhunt");
      dino.setDynamicProperty("compycraft_era:hunt", false);
    }
    if (r.formValues[2] != "") {
      dino.nameTag = `${r.formValues[2]}`;
      dino.setDynamicProperty("compycraft_era:name", r.formValues[2]);
    }
  });
}

export function GlobalMenuModal(player) {
  const menu = new ModalFormData();
  menu.title("§2Global Menu");
  menu.toggle("Dinosaur Spawns", true);
  if (world.getDynamicProperty("compycraft_era:eye") == undefined) {
    world.setDynamicProperty("compycraft_era:eye", 0);
  }
  menu.slider("Change eye style of all creatures", 0, 5, 1);

  menu.show(player).then((r) => {
    if (r.canceled) return;
    if (r.formValues[0] == true) {
      world.setDynamicProperty("compycraft_era:spawn", true);
    } else {
      world.setDynamicProperty("compycraft_era:spawn", false);
    }
    if (r.formValues[1] != undefined) {
      world.setDynamicProperty("compycraft_era:eye", r.formValues[1]);
    }
  });
}

world.afterEvents.itemUseOn.subscribe((eventData) => {
  const { source, block, itemStack } = eventData;
  const { x, y, z } = block.location;
  if (
    itemStack.typeId.includes("spawn_egg") &&
    world.getDynamicProperty("compycraft_era:spawn") == false
  ) {
    source.dimension
      .spawnEntity(`${itemStack.typeId.replace("_spawn_egg", "")}`, {
        x: x,
        y: y + 1,
        z: z,
      })
      .addTag(`egg_spawn`);
  }
});

world.afterEvents.entitySpawn.subscribe((eventData) => {
  let { entity } = eventData;
  if (entity.typeId.startsWith("compycraft_era:")) {
    if (entity?.getProperty("compycraft_era:sneak")) {
      entity.setProperty("compycraft_era:sneak", false);
    }
    if (world.getDynamicProperty("compycraft_era:spawn") == false) {
      if (!entity.hasTag("egg_spawn")) {
        system.runTimeout(() => {
          entity.remove();
        }, 0.25);
      }
    }
  }
});

system.runInterval(() => {
  const players = world.getAllPlayers();
  for (let player of players) {
    const filter = {
      //have two option here, place the "dinosaur" family in all dinos, or place all dinos family here
      location: {
        x: player.location.x,
        y: player.location.y,
        z: player.location.z,
      },
    };
    //player.runCommand("execute as @e[type=compycraft_era:hit_mob] at @s run particle minecraft:basic_flame_particle")
    for (const dino of player.dimension.getEntities(filter)) {
      if (dinosaurs.includes(dino.typeId)) {
        player.runCommand(
          "execute as @e[type=compycraft_era:hit_mob] at @s unless entity @e[family=player,r=12] run event entity @s despawn"
        );
        const rideEntity = dino
          ?.getComponent("minecraft:rideable")
          ?.getRiders()[0];
        if (rideEntity) {
          player.runCommand(
            "tp @e[type=compycraft_era:hit_mob] ^^1.5^2 facing ^^1.5^2"
          );
        }
        if (world.getDynamicProperty("compycraft_era:eye") != undefined) {
          if (dino.getProperty("compycraft_era:eye") != undefined) {
            dino.setProperty(
              "compycraft_era:eye",
              world.getDynamicProperty("compycraft_era:eye")
            );
          }
        }
      }
    }
  }
}, 5);
