"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.installBrowserDependencies = exports.downloadBrowserMaterial = exports.downloadZipInBrowser = exports.downloadZipInNode = exports.downloadZip = exports.downloadFile = void 0;
const axios_1 = __importDefault(require("axios"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const path = __importStar(require("path"));
const compressing_1 = __importDefault(require("compressing"));
const jszip_1 = __importDefault(require("jszip"));
const config_1 = require("../config");
const generateFiles_1 = require("../util/generateFiles");
const junk_1 = require("../util/junk");
async function downloadFile(url, filePath) {
    if (fs_extra_1.default.existsSync(filePath)) {
        return;
    }
    await fs_extra_1.default.ensureDir(path.dirname(filePath));
    const res = await axios_1.default.get(url, { responseType: 'arraybuffer' });
    fs_extra_1.default.writeFileSync(filePath, res.data);
}
exports.downloadFile = downloadFile;
/**
 * Download zip file and extract to dstDir
 * @param url
 * @param dstDir folder to hold the extract zip content
 */
async function downloadZip(url, dstDir, isBrowser = false, noCache = false) {
    // TODO 待加上平台判断
    if (isBrowser) {
        await downloadZipInBrowser(url, dstDir, noCache);
        return;
    }
    await downloadZipInNode(url, dstDir);
}
exports.downloadZip = downloadZip;
/**
 * node中下载和保存zip文件
 * @param url 下载的url
 * @param dstDir 存放文件夹
 */
async function downloadZipInNode(url, dstDir) {
    await fs_extra_1.default.ensureDir(dstDir);
    const res = await axios_1.default.get(url, { responseType: 'stream' });
    await compressing_1.default.zip.uncompress(res.data, dstDir);
}
exports.downloadZipInNode = downloadZipInNode;
/**
 * 浏览器中下载和保存zip文件
 * @param url 下载的url
 * @param dstDir 存放文件夹
 * @returns
 */
async function downloadZipInBrowser(url, dstDir, noCache) {
    // IMPORTANT 防止保存的时候保存
    if (!noCache && fs_extra_1.default.existsSync(dstDir)) {
        return;
    }
    fs_extra_1.default.ensureDirSync(dstDir);
    const res = await axios_1.default.get(url, { responseType: 'arraybuffer' });
    const data = await jszip_1.default.loadAsync(res.data);
    await saveFiles(data.files, dstDir);
}
exports.downloadZipInBrowser = downloadZipInBrowser;
/**
 * 保存JSZip解压的文件内容
 * @param files 文件
 * @param dstDir 指定目录
 */
async function saveFiles(files, dstDir) {
    try {
        for (const fileName of Object.keys(files)) {
            const dest = path.join(dstDir, fileName);
            if ((0, junk_1.isFilePath)(dest)) {
                continue;
            }
            if (files[fileName].dir) {
                // 如果该文件为目录需先创建文件夹
                if (!fs_extra_1.default.pathExistsSync(dest)) {
                    fs_extra_1.default.mkdirSync(dest, {
                        recursive: true,
                    });
                }
            }
            else {
                const ret = await files[fileName].async('nodebuffer'); // 由于这里有await，不能用forEach
                fs_extra_1.default.writeFileSync(dest, ret);
            }
        }
    }
    catch (err) {
        console.error('saveFiles catch error：', err);
    }
}
/**
 * 微信IDE builder需要下载template文件和miniprogram_npm
 * miniprogram_npm待微信提供端能力
 * @param output
 */
async function downloadBrowserMaterial({ runtimeEndpointType, browser = true, }) {
    const BUILD_TEMPLATES = require('../mp/template.json');
    await Promise.all([
        new Promise((resolve, reject) => {
            try {
                for (const key in BUILD_TEMPLATES) {
                    fs_extra_1.default.ensureFileSync(path.join(config_1.appTemplateDir, key));
                    fs_extra_1.default.writeFileSync(path.join(config_1.appTemplateDir, key), BUILD_TEMPLATES[key].code);
                }
                resolve(null);
            }
            catch (e) {
                reject(e);
            }
        }),
        runtimeEndpointType === 'tcb-api'
            ? downloadZip(config_1.cloudbaseMiniprogramURL, config_1.cloudbaseMiniprogramDir, browser)
            : downloadZip(config_1.miniprogramURL, config_1.miniprogramDir, browser),
        downloadZip(config_1.systemSubpackageMiniprogramURL, config_1.systemSubpackageMiniprogramDir, browser),
    ]);
}
exports.downloadBrowserMaterial = downloadBrowserMaterial;
async function installBrowserDependencies({ type, path: outPath, runtimeEndpointType, }) {
    // 必须先下载到.weapps-materials目录，因为.weapps-materials是默认下载目录，共享组件逻辑sharedMaterialsDir时会读取文件
    const MAP = {
        wedaRoot: runtimeEndpointType === 'tcb-api'
            ? {
                url: config_1.cloudbaseMiniprogramURL,
                src: config_1.cloudbaseMiniprogramDir,
            }
            : {
                url: config_1.miniprogramURL,
                src: config_1.miniprogramDir,
            },
        ['$weda_system']: {
            url: config_1.systemSubpackageMiniprogramURL,
            src: config_1.systemSubpackageMiniprogramDir,
        },
    };
    const meta = MAP[type];
    if (meta) {
        if (!fs_extra_1.default.existsSync(meta.src)) {
            await downloadZip(meta.url, path.join(outPath, 'miniprogram_npm'), true);
        }
        else {
            (0, generateFiles_1.copyRecursiveSync)(meta.src, path.join(outPath, 'miniprogram_npm'));
        }
    }
}
exports.installBrowserDependencies = installBrowserDependencies;
