import { world, system, ItemStack } from "@minecraft/server";

import { mythicusEvents } from "../events/main";

// UTILITY FUNCTIONS

system.afterEvents.scriptEventReceive.subscribe(({ id, sourceEntity }) => {
    if (id !== "mythicus_tw:tipFlags.reset" || sourceEntity?.typeId !== "minecraft:player") return;

    sourceEntity.setDynamicProperty("mythicus_tw:tipFlags", "".padStart(100, "0"));
});

export function getCharAtIndex(player, property, index, size = 100) {
    const chars = player.getDynamicProperty(property) ?? "".padStart(size, "0");
    return chars.charAt(index) ?? "";
}

export function setCharAtIndex(player, property, index, value = "1", size = 100) {
    const chars = player.getDynamicProperty(property) ?? "".padStart(size, "0");

    const charsUpd = chars.slice(0, index) + value + chars.slice(index + 1);
    player.setDynamicProperty(property, charsUpd);
}

//
const TIP_DELAY = {};

const TIP_DATA = {
    "mythicus_tw:hd": {
        index: 2,
        recurrence: 1,
        msg: "mythicus_tw:chat.tip.hotDepositBlock",
    },
    "mythicus_tw:crafter": {
        index: 3,
        recurrence: 1,
        msg: "mythicus_tw:chat.tip.crafterBlock",
    },
    "mythicus_tw:searcher": {
        index: 4,
        recurrence: 1,
        msg: "mythicus_tw:chat.tip.searcherBlock",
    },
    "mythicus_tw:smelter": {
        index: 5,
        recurrence: 1,
        msg: "mythicus_tw:chat.tip.smelterBlock",
    },
};



mythicusEvents.afterEvents.playerViewBlock.subscribe(({ player, block }) => {

    // return if player's tips are disabled
    if (!player.getDynamicProperty("mythicus_tw:addonSettings.tipsEnabled")) return;

    // check if add-on block
    if (block?.typeId?.startsWith("mythicus_tw") !== true) return;

    // check if block has associated tip
    const tipData = TIP_DATA[block.typeId];
    if (!tipData) return;

    // check tip count
    const tipCount = parseInt(getCharAtIndex(player, "mythicus_tw:tipFlags", tipData.index));
    if (tipCount >= tipData.recurrence) return;

    // check tip delay
    const tipDelay = TIP_DELAY[player.id];
    if (tipDelay) {
        const [delayIndex, delayTick] = tipDelay.split("::");
        if ((parseInt(delayTick) + 2400 * tipCount) >= system.currentTick) return;
    }
    TIP_DELAY[player.id] = `${tipData.index}::${system.currentTick + 200}`;

    // update tip
    setCharAtIndex(player, "mythicus_tw:tipFlags", tipData.index, String(tipCount + 1));
    player.sendMessage({ rawtext: [{ translate: tipData.msg, with: { rawtext: [{ translate: "mythicus_tw:chat.prefix" }] } }] });

});