const http = require("http");
const fs = require("fs");
const FormData = require("form-data");
const archiver = require("archiver")
const path = require('path')
var join = require('path').join;
const {rm, cp} = require('../../utils/shell')

module.exports.upload = async (modules) => {
    let modulesArr = modules.split(" ");

    modulesArr.forEach((module, index) => {
        let pageFolder = path.normalize(`${process.cwd()}/src/pages`);
        let moduleFolder = path.normalize(`${pageFolder}/${module}`);

        // modules文件夹存在就去做zip压缩，目前先跳过压缩直接上传已经压缩好的zip
        if (fs.existsSync(moduleFolder) && fs.existsSync(pageFolder)) {
            // findDirsAndZip(moduleFolder, module)
            zipDirs(pageFolder, module)
        } else {
            console.fatal("模块不存在")
        }
    });
};

/**
 * 上传zip
 * @param path zip路径
 * @param name 上传名称
 */
function uploadZip(path, name) {
    console.step(`上传${name}`)
    let fileStream = fs.createReadStream(path);
    let form = new FormData();
    form.append("file", fileStream);
    form.append("name", name);
    form.append("version", "0.0.1");// Version 后面需要从JSON里面获取
    form.append("description", "version1");

    const req = http.request(
        {
            host: "172.16.55.5",
            port: 3280,
            method: "POST",
            path: "/api/xupd/rn/upload",
            headers: form.getHeaders(),
        },
        (response) => {
            response.on('data', function (chunk) {
                let res = JSON.parse(chunk.toString());
                if (res.code === 10000) {
                    console.step(`上传${name}成功`)
                    // console.log('upload success.')
                    rm(path)
                    // updatefile.deleteFile(path)
                } else {
                    console.error(`上传${name}失败`)
                    // console.log('upload failed.')
                }
            });
        }
    );
    form.pipe(req);
}

/**
 * 获取文件夹并压缩
 * @param filePath
 */
function findDirsAndZip(filePath, moduleName) {
    //根据文件路径读取文件，返回文件列表
    function getFolders(path) {

        let files = fs.readdirSync(path);
        files.forEach(function (item, index) {
            let fPath = join(path, item);
            let stat = fs.statSync(fPath);
            if (stat.isDirectory()) {
                zipDirs(filePath, item)
            }
        });
    }

    getFolders(filePath)
}

/**
 * 压缩指定文件，完成后上传
 * @param dirParentPath
 * @param dirName
 */
async function zipDirs(dirParentPath, dirName) {
    console.step(`压缩${dirName}`);
    let zipPath = path.normalize(`${dirParentPath}/${dirName}.zip`);
    // console.log("=====" + zipPath)
    const output = fs.createWriteStream(zipPath);
    const archive = archiver('zip', {
        zlib: {level: 9}
    });
    output.on('close', function () {
        console.step(`压缩${dirName}完成${archive.pointer()} bytes`);
        // console.log('archiver has been finalized and the output file descriptor has closed.');
        uploadZip(zipPath, dirName)
        // rm(zipPath)
    });
    output.on('end', function () {
        console.log('Data has been drained');
    });
    // good practice to catch this error explicitly
    archive.on('error', function (err) {
        throw err;
    });
    archive.pipe(output);
    archive.directory(path.join(dirParentPath, dirName), dirName);
    archive.finalize();
}
