/*
 * Baxxon 
 * Copyright(c) 2000-2026 Lorne Taylor
 * MIT Licensed
 */

/**
 * Universal Background Service Utility
 * Handles automated intervals for both SPAs and MPAs.
 */
export default class Service {
    constructor(key, handler, options = {}) {
        this.key = key;
        this.handler = handler;
        this.op = { 
            freq: 10,       // frequency in seconds
            persistent: false, // If false, service stops when application is offline
            allowManual: false, // If true, UI renders a manual trigger button
            ...options 
        };
        this.interval = null;
        this.lastRun = null;
        this.statusMsg = "";
    }

    /**
     * Sets a custom status message to be displayed in the UI.
     */
    setStatusMsg(msg) {
        this.statusMsg = msg;
    }

    /**
     * Executes the service handler and updates timestamps.
     */
    run() {
        console.log(`[Service] Executing: ${this.key}`);
        this.handler();
        this.lastRun = Date.now();

        // If running as an interval, reset it to prevent double-run overlap
        if (this.interval && this.op.freq > 0) {
            this.stop();
            this.start(false);
        }
    }

    /**
     * Starts the service interval.
     * @param {boolean} immediate - If true, runs the handler once immediately before starting the interval.
     */
    start(immediate = true) {
        if (this.interval) return;
        
        console.log(`[Service] Starting: ${this.key}`);
        
        if (immediate) {
            this.run();
        }

        if (this.op.freq > 0) {
            this.interval = setInterval(() => {
                this.run();
            }, this.op.freq * 1000);
        }
    }

    /**
     * Stops the service interval.
     */
    stop() {
        if (this.interval) {
            clearInterval(this.interval);
            this.interval = null;
            console.log(`[Service] Stopped: ${this.key}`);
        }
    }

    /**
     * Returns the current status of the service.
     */
    getStatus() {
        return {
            key: this.key,
            isRunning: this.interval !== null || this.op.freq === 0,
            lastRun: this.lastRun,
            freq: this.op.freq,
            allowManual: this.op.allowManual,
            statusMsg: this.statusMsg
        };
    }
}
