"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const FS = require("fs");
const Path = require("path");
const Walk = require("walk");
const Parser = require("./falcon-parser");
const Utils = require("../../util/src");
const Capnp = require("./falcon-capnp");
class FalconBuilder {
    build(path, output, isProject = true) {
        return new Promise((resolve, rejects) => {
            const errMsgs = new Array();
            //  准备
            Utils.ACUtils.rmdirs(output);
            Utils.ACUtils.mkdirs(output);
            const parser = new Parser.Parser();
            //  解析转译
            const builders = new Array();
            const pickTplDistPath = (root) => {
                const manifest = JSON.parse(FS.readFileSync(Path.join(root, 'manifest.json')).toString());
                if (manifest.name) {
                    const distpath = Path.join(output, `${manifest.name}`);
                    if (!FS.existsSync(distpath)) {
                        FS.mkdirSync(distpath);
                    }
                    return distpath;
                }
                else {
                    return '';
                }
            };
            //  i18n / l10n
            const pickI18nInfo = (tplRoot) => {
                let i18n;
                Walk.walkSync(tplRoot, {
                    listeners: {
                        file: (root, stats, next) => {
                            if (stats.type === 'file' && Path.extname(stats.name) === '.json' && stats.name.indexOf('i18n') === 0) {
                                const data = JSON.parse(FS.readFileSync(Path.join(root, stats.name)).toString());
                                if (data) {
                                    if (i18n) {
                                        i18n = Object.assign(Object.assign({}, i18n), data);
                                    }
                                    else {
                                        i18n = data;
                                    }
                                }
                            }
                            next();
                        }
                    }
                });
                return i18n ? new Capnp.AI18nPhrases(i18n) : undefined;
            };
            Walk.walkSync(path, {
                listeners: {
                    file: (root, names, next) => {
                        if (names.type === 'file' && names.name === 'main.vue') {
                            builders.push(parser.parse(Path.join(root, names.name)).then((value) => __awaiter(this, void 0, void 0, function* () {
                                const distpath = pickTplDistPath(root);
                                value.meta = FS.readFileSync(Path.join(root, 'manifest.json')).toString();
                                const i18n = pickI18nInfo(root);
                                value.i18nPhrases = i18n;
                                const jsonpath = Path.join(distpath, `main.json`);
                                const binpath = Path.join(distpath, `main.bin`);
                                FS.writeFileSync(jsonpath, JSON.stringify(value, undefined, 2), { encoding: 'utf8' });
                                yield Capnp.build(jsonpath, binpath);
                            })).finally(() => {
                                next();
                            }));
                        }
                        else if (names.type === 'file' && Path.extname(names.name) === '.json' && names.name.indexOf('mock') === 0) {
                            const distpath = pickTplDistPath(root);
                            const mockpath = Path.join(distpath, 'main.mock');
                            let mock = new Array();
                            if (FS.existsSync(mockpath)) {
                                mock = JSON.parse(FS.readFileSync(mockpath).toString());
                            }
                            mock.push({
                                data: FS.readFileSync(Path.join(root, names.name)).toString()
                            });
                            FS.writeFileSync(mockpath, JSON.stringify(mock, undefined, 2), { encoding: 'utf8' });
                        }
                        else {
                            next();
                        }
                    },
                    errors: (root, names, next) => {
                        errMsgs.push(new Error('遍历编译路径失败'));
                        next();
                    }
                }
            });
            Promise.all(builders).then(results => {
                resolve('');
            }).catch(reason => {
                rejects(new Error(errMsgs.length !== 0 ? `${errMsgs.join('\n')}` : ''));
            });
        });
    }
}
exports.FalconBuilder = FalconBuilder;
//# sourceMappingURL=falcon-builder.js.map