"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const Util_1 = require("../../shared/Util");
const ObjectParser_1 = require("../../shared/utils/ObjectParser");
class BackgroundServicesFile {
    /** Read and parse the file asynchronously */
    static readFile(jsonFolder, onError) {
        return new Promise((resolve, reject) => {
            Util_1.readJsonFile(path.join(jsonFolder, BackgroundServicesFile.filePath), BackgroundServicesFile.fileEncoding)
                .then(json => resolve(parseBackProcessInfoFile(json, onError)))
                .catch(reject);
        });
    }
}
/** Path to the background services file (relative to the flashpoint root folder) */
BackgroundServicesFile.filePath = './services.json';
/** Encoding used by background services file */
BackgroundServicesFile.fileEncoding = 'utf8';
exports.BackgroundServicesFile = BackgroundServicesFile;
function parseBackProcessInfoFile(data, onError) {
    let parsed = {
        redirector: undefined,
        fiddler: undefined,
        server: undefined,
        start: [],
        stop: [],
    };
    const parser = new ObjectParser_1.ObjectParser({
        input: data,
        onError: onError ? ((e) => { onError(`Error while parsing Services: ${e.toString()}`); }) : noop
    });
    parsed.redirector = parseBackProcessInfo(parser.prop('redirector'));
    parsed.fiddler = parseBackProcessInfo(parser.prop('fiddler'));
    parsed.server = parseBackProcessInfo(parser.prop('server'));
    parser.prop('start').array(item => parsed.start.push(parseBackProcessInfo(item)));
    parser.prop('stop').array(item => parsed.stop.push(parseBackProcessInfo(item)));
    return parsed;
}
function parseBackProcessInfo(parser) {
    let parsed = {
        path: '',
        filename: '',
        arguments: [],
        kill: false,
    };
    parser.prop('path', v => parsed.path = str(v));
    parser.prop('filename', v => parsed.filename = str(v));
    parser.prop('kill', v => parsed.kill = !!v, true);
    parser.prop('arguments').arrayRaw(item => parsed.arguments.push(str(item)));
    return parsed;
}
/** Coerce anything to a string */
function str(str) {
    return (str || '') + '';
}
function noop() { }
//# sourceMappingURL=BackgroundServicesFile.js.map