#!/usr/bin/env node

console.error = function () { }

var file = require('../lib/file');
var path = require('path');

var args = process.argv.slice(2);

var [dir1, dir2] = args;

if (dir1 === undefined || dir2 === undefined) {
    console.log('diff用于比较2个目录差异，必须指定2个目录')
}

async function getMd5(files) {
    var filesMd5 = [];
    for (var i = 0; i < files.length; i++) {
        var md5 = await file.Md5(files[i]);
        filesMd5.push(md5);
    }
    return filesMd5
}

(async () => {
    var isDir1 = await file.IsDir(dir1);
    var isDir2 = await file.IsDir(dir2);
    if (!isDir1 || !isDir2) {
        console.log('diff用于比较2个目录差异，必须指定2个目录')
    }

    var filesDir1 = await file.ReadDir(dir1);
    var filesDir2 = await file.ReadDir(dir2);

    // 先比较文件名
    let temp1 = filesDir1.map(f => f.replace(dir1, ''));
    let temp2 = filesDir2.map(f => f.replace(dir2, ''));
    let onlyInDir1 = [];
    let onlyInDir2 = [];
    let diffFiles1 = [];
    let diffFiles2 = [];
    temp1.forEach((fileName, index) => {
        if (temp2.includes(fileName)) {
            diffFiles1.push(path.join(dir1, fileName))
            diffFiles2.push(path.join(dir2, fileName))
        } else {
            onlyInDir1.push(path.join(dir1, fileName))
        }
    });
    temp2.forEach((fileName, index) => {
        if (!temp1.includes(fileName)) {
            onlyInDir2.push(path.join(dir2, fileName))
        }
    });

    var md5_1 = await getMd5(diffFiles1);
    var md5_2 = await getMd5(diffFiles2);
    var diffFiles = [];

    md5_1.forEach((hash, index) => {
        if (!md5_2.includes(hash)) {
            diffFiles.push(diffFiles1[index])
        }
    })

    var result = ""
    var diff = false;
    if (onlyInDir1.length > 0) {
        diff = true;
        result += `----------
仅存在  ${dir1}
----------
${onlyInDir1.join('\r\n')}

`
    }
    if (onlyInDir2.length > 0) {
        diff = true;
        result += `----------
仅存在  ${dir2}
----------
${onlyInDir2.join('\r\n')}

`
    }
    if (diffFiles.length > 0) {
        diff = true;
        result += `----------
有差异 
----------
${diffFiles.join('\r\n')}`
    }
    if (diff) {
        console.log(result)
    } else {
        console.log("目录完全一致")
    }

})()