import path from "path";
import { Worker } from 'worker_threads';
import { fileURLToPath } from 'url';

/**
 *
 * @param templatePath
 * @param avatarURL
 * @param username
 * @returns {Promise<unknown>}
 */
function launchWorker({ templatePath, avatarURL, username }) {
    return new Promise((resolve, reject) => {

        const filename = fileURLToPath(import.meta.url);
        const dirname = path.dirname(filename);
        const workerFile = path.join(dirname, 'nameCardWorker.js');

        const worker = new Worker(workerFile);

        worker.postMessage({ templatePath, avatarURL, username });

        worker.once('message', async (result) => {
            resolve(result);
        });

        worker.once('error', async (err) => {
            reject(err);
        });

        worker.once('exit', async (code) => {
            if (code === 0) {
                console.log('Worker exited cleanly.');
            } else {
                console.warn('Worker exited with error code:', code);
            }
        });
    });
}


export {launchWorker}

