"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.launchLocalKraken = exports.patchPolyfill = exports.triggerDebugLayout = void 0;
const child_process_1 = require("child_process");
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const which_1 = __importDefault(require("which"));
const temp_1 = __importDefault(require("temp"));
const prettier_1 = __importDefault(require("prettier"));
const parser_babel_1 = __importDefault(require("prettier/parser-babel"));
const kill = require('tree-kill');
const polyFill = fs_1.default.readFileSync(path_1.default.join(__dirname, './polyfill.js'), { encoding: 'utf-8' });
let runningProcess = [];
let currentContent;
async function triggerDebugLayout(debug) {
    return new Promise(async (resolve, reject) => {
        if (!currentContent) {
            return;
        }
        if (runningProcess.length == 0)
            return;
        while (runningProcess.length > 0) {
            let childProcess = runningProcess.pop();
            kill(childProcess.pid);
        }
        const krakenPath = await which_1.default('kraken');
        let code = currentContent;
        temp_1.default.open({ suffix: '.js' }, (err, info) => {
            if (err)
                return reject(err);
            let path = info.path;
            fs_1.default.writeFile(path, code, (err) => {
                if (err)
                    return reject(err);
                console.log('starting kraken at ' + path);
                let child = child_process_1.fork(krakenPath, [path, debug ? '-d' : ''], { stdio: 'inherit' });
                runningProcess.push(child);
                resolve();
            });
        });
    });
}
exports.triggerDebugLayout = triggerDebugLayout;
function patchPolyfill(targetDir, spec) {
    let originalCode = spec.content;
    originalCode = originalCode.replace(/assets\//g, 'https://kraken.oss-cn-hangzhou.aliyuncs.com/images/');
    console.log(originalCode);
    let code = `
  // test file: ${targetDir}/${spec.suitName}.ts
  // it: ${spec.name}

  let BODY = document.body;
  BODY.style.margin = '0px';

  ${originalCode}

  ${polyFill}
      `;
    try {
        return prettier_1.default.format(code, {
            singleQuote: true,
            tabWidth: 2,
            parser: 'babel',
            plugins: [parser_babel_1.default]
        });
    }
    catch (e) {
        return code;
    }
}
exports.patchPolyfill = patchPolyfill;
async function launchLocalKraken(targetDir, spec) {
    return new Promise(async (resolve, reject) => {
        let code = patchPolyfill(targetDir, spec);
        currentContent = code;
        const krakenPath = await which_1.default('kraken');
        while (runningProcess.length > 0) {
            let childProcess = runningProcess.pop();
            kill(childProcess.pid);
        }
        temp_1.default.open({ suffix: '.js' }, (err, info) => {
            if (err)
                return reject(err);
            let path = info.path;
            fs_1.default.writeFile(path, code, (err) => {
                if (err)
                    return reject(err);
                console.log('starting kraken at ' + path);
                let child = child_process_1.fork(krakenPath, [path], { stdio: 'inherit' });
                runningProcess.push(child);
                resolve();
            });
        });
    });
}
exports.launchLocalKraken = launchLocalKraken;
