/*
----------------------------------
Creator: Mafly
Discord:
https://discord.gg/BUFxackwWb
Youtube: MaFly
https://www.youtube.com/c/MaFly16

Website:
https://mcblibrary.com/user/mafly
----------------------------------
*/

/* EXAMPLE OF COMMAND BUILD REGISTER
CommandBuild.register(
  {
    name: "help", //required, only letters and cannot be the same as existing ones
    aliases: ["h"], //optional, can be left blank
    description: "Provides help/list of commands.", //required, can use strings
    usage: "<page: number>", //optional, can be left blank
    admin: false, //optional, boolean default is false
    permission: ["vip"], //optional, can be left blank
  },
  (data, player, args) => {
    //something to be executed
    player.sendMessage("Example command!!")
  }
);
END COMMAND BUILD REGISTER*/

import { world, system } from "@minecraft/server";
import { CommandBuild } from "../function/CommandBuild.js";
import { config } from "./config.js";

world.beforeEvents.chatSend.subscribe((data) => {
  if (data.message.startsWith(config.prefix)) {
    let args = data.message.slice(config.prefix.length).trim().split(" ");
    let command = args.shift().toLowerCase();
    const player = data.sender;
    data.cancel = true;

    if (CommandBuild.valid(command, player)) {
      let getCommand = CommandBuild.getRegistration(command);
      getCommand.callback(data, player, args, getCommand);
    }
  }
});

CommandBuild.register(
  {
    name: "help",
    aliases: ["h"],
    description: "Provides help/list of commands.",
    usage: "<page: int>",
  },
  (data, player, args) => {
    const page = Math.max(parseInt(args[0]) || 1, 1);
    const list = 10;
    const start = (page - 1) * list;
    const end = page * list;

    const getCommands = CommandBuild.getAllRegistration()
      .filter((command) => !command.admin || player.hasTag("admin"))
      .sort((a, b) => a.name.localeCompare(b.name));

    const total = Math.ceil(getCommands.length / list);

    if (page > total) {
      system.run(() => {
        player.sendMessage(
          `§cSYSTEM §7>> §cInvalid page number. Please enter a number between 1 to ${total}.`
        );
        player.playSound("note.bass");
      });
      return;
    }

    let message = `§7>>-----<< §gShowing help page ${page} of ${total} §7>>-----<<`;
    for (let i = start; i < end && i < getCommands.length; i++) {
      let command = getCommands[i];
      message += `\n§r§g${config.prefix}${command.name} ${
        command.usage ? command.usage + " " : ""
      }§7>> §o${command.description}`;
    }
    player.sendMessage(
      `§7>>-----<< §g[Mafly] Custom Command V3 §7>>-----<<\n\n§cDiscord §7>> §bhttps://discord.gg/BUFxackwWb\n§cYouTube §7>> §bhttps://youtube.com/c/MaFly16\n§cWebsite §7>> §bhttps://mcblibrary.com/user/Mafly\n\n${message}`
    );
    system.run(() => player.playSound("random.pop"));
  }
);
