"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());
    });
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const Path = __importStar(require("path"));
const FS = __importStar(require("fs"));
const Utils = __importStar(require("../../util/src"));
const Connect = __importStar(require("../../connect/src"));
var ProjectType;
(function (ProjectType) {
    ProjectType["None"] = "none";
    ProjectType["Falcon"] = "falcon";
    ProjectType["Vue"] = "vue";
    ProjectType["Appx"] = "appx"; //  小程序工程
})(ProjectType || (ProjectType = {}));
const handlers = Object.create(null);
handlers[ProjectType.Falcon] = previewFalcon;
handlers[ProjectType.Vue] = previewVue;
handlers[ProjectType.Appx] = previewAppx;
function preview(path) {
    return __awaiter(this, void 0, void 0, function* () {
        Utils.Console.info(`预览工程 [${path}]`);
        if (Connect.clientSessions().length > 0) {
            const func = handlers[pjtype(path)];
            if (func) {
                yield func(path);
                return Promise.resolve();
            }
            else {
                return Promise.reject(Error(`未找到可预览工程`));
            }
        }
        else {
            return Promise.reject(Error(`未找到连接设备`));
        }
    });
}
exports.preview = preview;
function pjtype(path) {
    const pkgPath = Path.join(path, 'package.json');
    if (FS.existsSync(pkgPath)) {
        const pkg = JSON.parse(FS.readFileSync(pkgPath).toString());
        if (!pkg.type || pkg.type === 'tinyapp') {
            return ProjectType.Appx;
        }
        else if (pkg.type && pkg.type === 'application') {
            return ProjectType.Vue;
        }
        else if (pkg.type && pkg.type === 'templates') {
            return ProjectType.Falcon;
        }
    }
    return ProjectType.None;
}
function previewFalcon(path) {
    const pkg = JSON.parse(FS.readFileSync(Path.join(path, 'package.json')).toString());
    if (FS.existsSync(Path.join(path, '/dist'))) {
        const payload = Object.assign({}, pkg);
        payload.templates = new Array();
        Utils.FS.walk(Path.join(path, '/dist'), (root, name, stats) => {
            if (stats.isFile() && Path.extname(name) === '.bin') {
                const main = JSON.parse(FS.readFileSync(Path.join(root, 'main.json')).toString());
                const manifest = JSON.parse(main.meta);
                const tpl = Object.assign({}, manifest);
                tpl.version = `${manifest.version}__${(new Date()).getTime()}`;
                tpl.description = undefined;
                tpl.from = 'IDE';
                tpl.file_bin = Connect.fillFileRemoteUrl(Path.join(root, 'main.bin'));
                tpl.file_json = Connect.fillFileRemoteUrl(Path.join(root, 'main.json'));
                tpl.file_zst = Connect.fillFileRemoteUrl(Path.join(root, 'main.zst'));
                if (FS.existsSync(Path.join(root, 'main.mock'))) {
                    tpl.datas = JSON.parse(FS.readFileSync(Path.join(root, 'main.mock'), { encoding: 'utf8' }).toString());
                }
                else {
                    tpl.datas = [];
                }
                payload.templates.push(tpl);
            }
        });
        if (payload.splitMock === true) {
            payload.subtype = 'list';
            let maxMockCount = 0;
            for (const tpl of payload.templates) {
                maxMockCount = maxMockCount > tpl.datas.length ? maxMockCount : tpl.datas.length;
            }
            const templates = new Array();
            for (let index = 0; index < maxMockCount; index++) {
                for (const tpl of payload.templates) {
                    if (index < tpl.datas.length) {
                        const splitTpl = Object.assign({}, tpl);
                        splitTpl.datas = [tpl.datas[index]];
                        templates.push(splitTpl);
                    }
                }
            }
            payload.templates = templates;
        }
        Connect.broadcase(JSON.stringify({
            key: 'show_project_templates',
            payload
        }));
        return Promise.resolve();
    }
    else {
        return Promise.reject(Error(`未找到Cube编译产物`));
    }
}
function previewVue(path) {
    const zippath = Path.join(path, '/dist/compress/mQAppId.zip');
    if (FS.existsSync(zippath)) {
        const pkg = JSON.parse(FS.readFileSync(Path.join(path, 'package.json')).toString());
        Connect.broadcase(JSON.stringify({
            key: 'show_project_application',
            payload: {
                name: pkg.name,
                type: pkg.type,
                subtype: pkg.subtype,
                source: Connect.fillFileRemoteUrl(zippath)
            }
        }));
        return Promise.resolve();
    }
    else {
        return Promise.reject(new Error(`未找到Cube编译产物 [${zippath}]`));
    }
}
function previewAppx(path) {
    return __awaiter(this, void 0, void 0, function* () {
        const nativePath = Path.join(path, 'dist/native');
        const zipPath = Path.join(path, 'dist/native.zip');
        Utils.Console.info(`准备投递小程序编译产物 [${nativePath}]`);
        if (FS.existsSync(nativePath)) {
            yield Utils.FS.zip(nativePath, zipPath);
            Utils.Console.info(`压缩小程序编译产物 [${zipPath}]`);
            const pkg = JSON.parse(FS.readFileSync(Path.join(path, 'package.json')).toString());
            Connect.broadcase(JSON.stringify({
                key: 'show_project_tinyapp',
                payload: {
                    name: pkg.name,
                    type: 'tinyapp',
                    source: Connect.fillFileRemoteUrl(zipPath)
                }
            }));
            return Promise.resolve();
        }
        else {
            return Promise.reject(Error(`未找到Cube编译产物 [${nativePath}]`));
        }
    });
}
//# sourceMappingURL=preview.js.map