import fs from "fs";
import path from "path";
import {fileURLToPath} from 'url';
import {execFile} from "child_process";
const __dirname = fileURLToPath(new URL('.', import.meta.url));

const picoDirPath = path.resolve(__dirname, "..", "..", "..", "pico8");
const picoBinPath = path.resolve(picoDirPath, "pico8_dyn");

const cmd = (cmd: string, args: string[], options = {}) => {
	return new Promise((resolve, reject) => {
		execFile(cmd, args, options, (error, stdout, stderr) => {
			if (error) {
				reject({error, stderr});
			} else {
				resolve({stdout});
			}
		})
	});
}

const execPico = async (args: string[]) => {
	return await cmd(picoBinPath, args);
}

export const pico8 = {
	async export(fileIn: string, fileOut: string) {
		try {
			// console.log((await cmd("ls", ["-la", "/app/pico8"]) as any).stdout)
			return await execPico([fileIn, "-export", fileOut]);
		} catch (err) {
			console.log("CAUGHT ERROR", err);
		}
	}
}

// const result = await pico8.export("/home/dylan/.lexaloffle/pico-8/carts/my-pico-project/mygame.p8", "/home/dylan/repos/picobook/sample.js");
// console.log(result);