/*
 * @Author: 莫靓仔
 * @description: 文件描述
 * @Date: 2021-09-02 11:27:54
 * @LastEditors: 莫靓仔
 * @LastEditTime: 2021-09-03 19:54:30
 */
const path = require('path')
const fs = require('fs')
const os = require('os')
const del = require('del')
const JsZip = require('jszip')
const zip = new JsZip()
const chalk = require('chalk')
const compressing = require('compressing')
// 要压缩的文件夹目录
const sourceDir = path.join(__dirname, '../dist')
// 生成压缩包的目录
const targetDir = path.join(__dirname, './tmp/dist.zip')

function starTarGz() {
    console.log(chalk.blue('正在压缩...'))
    // 流写法
    // function handleError(err) {
    //     console.log(err)
    // }
    // const tarStream = new compressing.tar.Stream()
    // tarStream.addEntry('dist/bi')
    // tarStream.on('error', handleError).pipe(fs.createWriteStream('./config/tmp/dist.tar')).on('error', handleError)

    // new compressing.tar.FileStream({ source: path.resolve('../dist/bi') })
    //     .on('error', handleError)
    //     .pipe(fs.createWriteStream('./config/tmp/dist.tar'))
    //     .on('error', handleError)

    // // It's a transform stream, so you can pipe to it
    // fs.createReadStream('dist/bi')
    //     .on('error', handleError)
    //     .pipe(new compressing.tar.FileStream())
    //     .on('error', handleError)
    //     .pipe(fs.createWriteStream('./config/tmp/dist.tar'))
    //     .on('error', handleError)

    // promise写法
    compressing.tar
        .compressDir('dist/bi', './config/tmp/dist.tar')
        .then(res => {
            console.log(chalk.green('tar压缩完成！'))
            compressing.gzip
                .compressFile('./config/tmp/dist.tar', './config/tmp/dist.tar.gz')
                .then(() => {
                    console.log(chalk.green('gz压缩完成！'))
                    del.sync(path.join(__dirname, './tmp/dist.tar'))
                })
                .catch(err => {
                    console.log(chalk.red('gz压缩失败！'), err)
                })
        })
        .catch(err => {
            console.log(chalk.red('tar压缩失败！'))
            console.log(err)
        })
}

// 读取目录及文件
function readDir(zipObj, nowPath, nowFolder) {
    // 读取目录中的所有文件及文件夹
    let files = fs.readdirSync(nowPath)
    files.forEach(fileName => {
        // 遍历检测目录中的文件
        let filePath = `${nowPath}/${fileName}`
        let file = fs.statSync(filePath)
        if (file.isDirectory()) {
            // 如果是文件夹，继续读取
            let path = `${nowPath}/${fileName}`
            // 压缩对象中生成该目录，replace是为了去掉前面的系统目录
            let dirList = zip.folder(path.replace(`${sourceDir}`, ''))
            // let dirList = zip.folder(filePath.replace(`${__dirname}/dist/`, ''))
            // 重新检索目录文件
            readDir(dirList, filePath)
        } else {
            // 如果是文件则压缩
            zipObj.file(fileName, fs.readFileSync(filePath))
        }
    })
}

// 开始压缩文件
function startZIP() {
    console.log(chalk.blue('正在压缩...'))
    // 先清掉原来的
    del.sync(targetDir)
    // 读取文件，往zip中塞东西
    readDir(zip, sourceDir, '')
    zip.generateAsync({
        type: 'nodebuffer',
        compression: 'DEFLATE',
        compressionOptions: {
            level: 9
        }
    })
        .then(content => {
            fs.writeFile(targetDir, content, 'utf-8', err => {
                if (err) {
                    throw err
                }
                console.log(chalk.green('压缩完成！'))
            })
        })
        .catch(err => {
            console.log(err)
        })
}

if (os.type() == 'Windows_NT') {
    // zip压缩
    startZIP()
} else {
    // 使用tar.gz格式（Linux系统识别），zip为windows的格式
    // https://github.com/npm/node-tar
    // https://www.npmjs.com/package/compressing
    starTarGz()
}
