const gulp = require("gulp");
const fs = require("fs-extra");
const { src, dest } = require("gulp");
const gulpIgnore = require("gulp-ignore");
const md5 = require("blueimp-md5");
const gulpBabel = require("gulp-babel");
const path = require("path");
const sourceMap = require('gulp-sourcemaps');

const files = {};
const changedFiles = [];

// 指定忽略的文件
const ignoreFiles = ['common/signature/'];

// 一些特征文件名忽略
const ignoreFilesReg = [
    '.min.js',
    '-min.js',
    'jquery',
    'jQuery',
    'signApp.js'
]

function ifIgnoreFile(file) {
    for (let i = 0; i < ignoreFiles.length; i++) {
        const path = file.path.replace(/\\/g, '/');
        if (path.includes(ignoreFiles[i])) {
            return true;
        }
    }
    const filename = path.basename(file.path);
    // 忽略文件新增

    for (let i = 0; i < ignoreFilesReg.length; i++) {
        const reg = ignoreFilesReg[i];
        if (new RegExp(reg, 'g').test(filename)) {
            return true;
        }
    }
    // return filename.includes(".min.js") || filename.includes("-min.js");
    return false;
}

function srcOldFileMD5(file) {
    const data = fs.readFileSync(file.path, "utf-8");
    if (!(file.path in files)) {
        files[file.path] = md5(data);
    }
    return false;
}

function srcNewFileMD5(file) {
    const data = fs.readFileSync(file.path, "utf-8");
    const newMD5 = md5(data);
    const oldMD5 = files[file.path]
    if (oldMD5 !== newMD5) {
        changedFiles.push(file.path)
    }
    return true;
}


function es62es5() {
    return src(path.join(process.argv[process.argv.length - 1], './src/**/*.js'))
        .pipe(sourceMap.init())
        .pipe(gulpIgnore.exclude(ifIgnoreFile))
        .pipe(gulpIgnore.exclude(srcOldFileMD5))
        .pipe(gulpBabel({
            presets: [
                ['@babel/preset-env', {
                    "targets": {
                        "browsers": ["IE > 8"]
                    },
                    "modules": false
                }],
            ],
            plugins: [["@babel/plugin-transform-modules-commonjs", { "strictMode": false }]],
            overrides: [{ sourceType: "script"}],
            sourceType: 'script'
        }))
        .pipe(sourceMap.write('./',{addComment: true}))
        .pipe(dest(coverFile), {
            overwrite: true
        })
        .pipe(gulpIgnore.exclude(srcNewFileMD5))

}

function consoleLogger(cb) {
    console.log("============= 变更文件 ===============")
    changedFiles.forEach(f => console.log(f))
    console.log("============= 总计：" + changedFiles.length + " ===============")
    cb();
}

// 覆盖源文件
function coverFile(file) {
    return file.base;
}

exports.default = gulp.series(es62es5, consoleLogger)