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



export class ActionbarTimer {
    #player;
    #handler;

    /**
     * @param {Player} player
     * @param {number} maxTime - time in ticks
     * @param {IndicatorType} indicatorType - type of indicator
     */
    constructor(player, maxTime, indicatorType = 'bar') {
        this.#player = {
            player,
            maxTime,
            currentTime: 0,
            indicatorType
        };
        this.#loadingIndicator();
    }

    #loadingIndicator() {
        this.#handler = system.runInterval(() => {
            this.#player.currentTime = Math.min(this.#player.currentTime + 1, this.#player.maxTime);

            if (this.#player.indicatorType === 'bar') {
                // Calculate progress percentage
                const progress = Math.floor((this.#player.currentTime / this.#player.maxTime) * 100);
                const completedBars = Math.floor(progress / 10);
                const remainingBars = 10 - completedBars;

                // Generate the green and red bar segments
                const greenBars = `§a${'█'.repeat(completedBars)}`; // Green for completed portion
                const redBars = `§c${'█'.repeat(remainingBars)}`;   // Red for remaining portion

                // Update action bar with colored indicator
                this.#player.player.runCommand(`title @s actionbar ${greenBars}${redBars}`);
            } else if (this.#player.indicatorType === 'number') {
                // Update action bar with a numeric indicator
                this.#player.player.runCommand(`title @s actionbar ${this.#player.currentTime}/${this.#player.maxTime}`);
            }
        });

    }

    stop() {
        system.clearRun(this.#handler);
        this.#player.player.runCommand('title @s actionbar  ');
        this.#player = null;
        this.#handler = null;
    }
}



/**
 * @typedef {'bar' | 'number'} IndicatorType
 */