const fs = require('fs');
const path = require('path');
const gulp = require('gulp');

const babel = require('gulp-babel');
const concat = require('gulp-concat');
const rename = require('gulp-rename');
const uglify = require('gulp-uglify');
const minimist = require('minimist');
const stripdebug = require('gulp-strip-debug');
const merge = require('merge-stream');


const knownOptions = { string: 'indexview' };
const options = minimist(process.argv.slice(3), knownOptions);
const rootPath = 'src';

/**
 * 获取视图文件路径
 * 
 */
function getAllViewTools() {
    let allTxtFiles = [];
    fs.readdirSync(rootPath).filter((moduleFolder) => {
        return fs.statSync(path.join(rootPath, moduleFolder)).isDirectory();
    }).forEach((moduleFolder) => {
        // 模块文件夹路径 （相对）
        let moduleFolderPath = path.join(rootPath, moduleFolder);
        fs.readdirSync(moduleFolderPath).filter((viewFolder) => {
            return fs.statSync(path.join(moduleFolderPath, viewFolder)).isDirectory();
        }).forEach((viewFolder) => {
            // 视图文件夹路径 （相对）
            let viewFolderPath = path.join(moduleFolderPath, viewFolder);
            fs.readdirSync(viewFolderPath).forEach((file) => {
                if (fs.statSync(path.join(viewFolderPath, file)).isFile()) {
                    allTxtFiles.push(path.join(viewFolderPath, file));
                }
            });
        });
    });
    return allTxtFiles;
}

/**
 * 处理合并文件
 * 
 * 
 * @param {*} contant 
 */
function translateMergeFiles(contant) {
    let viewInfo = { viewname: '', suburl: '', tempurl: '', refviews: [] };
    let contant_arr = JSON.parse(JSON.stringify(contant.replace(/\r?\n/g, '').split(';')));
    if (contant_arr.length !== 4) {
        return;
    }

    viewInfo.viewname = contant_arr[0];
    viewInfo.suburl = contant_arr[1];
    viewInfo.tempurl = contant_arr[2];

    let refviews = JSON.parse(JSON.stringify(contant_arr[3].split(',')));
    refviews.forEach((refview) => {
        if (fs.existsSync(path.join('../pages', refview))) {
            viewInfo.refviews.push(path.join('../pages', refview));
        }
    });

    if (Object.is(viewInfo.viewname, '') || Object.is(viewInfo.suburl, '') || viewInfo.refviews.length === 0) {
        console.error(JSON.stringify(viewInfo))
    }

    viewInfo.suburl = path.join('../pages', viewInfo.suburl);
    viewInfo.tempurl = path.join('dist', viewInfo.tempurl);

    return viewInfo;
}

// r2 编译打包处理
gulp.task('r2', function () {
    var txts = getAllViewTools();
    var subtask = txts.map((txt) => {
        try {
            let contant = fs.readFileSync(txt, 'UTF-8');
            let viewInfo = translateMergeFiles(contant);
            console.time(viewInfo.viewname);
            return gulp.src(viewInfo.refviews)
                .pipe(babel({
                    presets: ['@babel/env']
                }))
                .pipe(concat(viewInfo.viewname + '-allrefview.js'))
                .pipe(stripdebug())
                .pipe(uglify())
                .pipe(rename({ suffix: '.min' }))
                .pipe(gulp.dest(viewInfo.suburl))
                .on('error', (err) => {
                    console.log(err);
                    console.timeEnd(viewInfo.viewname);
                })
                .on('end', () => {
                    console.timeEnd(viewInfo.viewname);
                });
        } catch (error) {
            console.log(error);
        }
    });

    return merge(subtask);
});


// 拆分单页应用首页关联视图
gulp.task('splitsp', () => {
    let contant = fs.readFileSync(path.join(rootPath, options.indexview), 'UTF-8');
    let viewInfo = translateMergeFiles(contant);

    let allrefviews = [];
    const split_length = 200;

    for (var i = 0; i < viewInfo.refviews.length; i += split_length) {
        allrefviews.push(viewInfo.refviews.slice(i, i + split_length));
    }

    var subtask = allrefviews.map((subrefview, index) => {
        try {
            console.time(index);
            return gulp.src(subrefview)
                .pipe(babel({
                    presets: ['@babel/env']
                }))
                .pipe(concat(index + '.js'))
                .pipe(stripdebug())
                .pipe(uglify())
                .pipe(rename({ suffix: '.min' }))
                .pipe(gulp.dest(viewInfo.tempurl))
                .on('error', (err) => {
                    console.log(err);
                    console.timeEnd(index);
                })
                .on('end', () => {
                    console.timeEnd(index);
                });
        } catch (error) {
            console.log(error);
        }
    });

    return merge(subtask);
});

// 单页编译打包处理
gulp.task('sp', ['splitsp'], () => {
    let contant = fs.readFileSync(path.join(rootPath, options.indexview), 'UTF-8');
    let viewInfo = translateMergeFiles(contant);

    console.time(viewInfo.viewname);
    return gulp.src(viewInfo.tempurl + '**.js')
        .pipe(concat(viewInfo.viewname + '-allrefview.js'))
        .pipe(uglify())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest(viewInfo.suburl))
        .on('error', (err) => {
            console.log(err);
            console.timeEnd(viewInfo.viewname);
        })
        .on('end', () => {
            console.timeEnd(viewInfo.viewname);
        });
});
