import { Player, system, world } from "@minecraft/server";
import { config, sendPlayerMessage } from "../config";
import { lifestealLogs } from "../lifesteal";

export interface commandData {
    /**
     * Name of the command
     */
    name: string;
    /**
     * Aliases for the command
     */
    aliases?: string[];
    /**
     * Whether its staff only or not
     */
    staffOnly?: boolean;
    /**
     * Whether only ghosts can use it or not
     */
    ghostsOnly?: boolean;
    /**
     * Code for the command
     */
    code: (data: { player: Player, args: string[], commandName: string; }) => void;
};

/**
 * Make a new command
 */
export class Command {
    static readonly commands: commandData[] = [];
    constructor(commandInfo: commandData) {
        if (!Command.commands.includes(commandInfo)) Command.commands.push(commandInfo);
    }
}

export const commands: commandData[] = Command.commands;

world.beforeEvents.chatSend.subscribe(data => {
    if (data.message.startsWith(config.prefix)) {
        data.cancel = true;
        const args = data.message.slice(config.prefix.length).toLowerCase().split(/\s+/g);
        const command = args.shift();

        const cmdData = commands.find(c => c.name.toLowerCase() === command.toLowerCase() || c.aliases?.includes(command.toLowerCase()));
        if (!cmdData) return sendPlayerMessage(data.sender, `§cUnknown command: ${command}. Do ${config.prefix}help for a list of commands`);
        if (cmdData.staffOnly && !data.sender.hasTag(config.staffTag) && !data.sender.isOp()) return sendPlayerMessage(data.sender, `§cYou do not have permission to run this command!`);

        if (cmdData.ghostsOnly && !data.sender.hasTag(`ls-dead`)) return sendPlayerMessage(data.sender, `§cOnly ghosts can run this command!`);

        const player = data.sender;

        system.run(() => {
            cmdData.code({ player, args, commandName: command });
        });

        const hours = new Date().getUTCHours();
        const minutes = new Date().getUTCMinutes();
        const date = `${hours > 12 ? hours - 12 : hours}:${minutes} ${hours >= 12 && hours !== 24 ? `PM` : `AM`}`;
        lifestealLogs.push(`§6${date} > ${data.sender.name} used - ${data.message}`);
    }
});