#!/usr/bin/env node
/**
 * @license
 * Copyright Google LLC All Rights Reserved.
 * 
 * npm install --save-dev colors
 * npm install --save-dev iconv-lite
 */

 'use strict';

 require('colors');
 
const readline = require('readline');
const { exec } = require("child_process");

const fs = require('fs-extra');

const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout,
});

function showValidString(errorLogs, title, pathName) {
    const stderrLines = [];
    let successCnt = 0;
    let warnCnt = 0;
    
    errorLogs.split("\n").forEach(function(line) {
        if (line.length > 0 && !line.startsWith('npx: ')) {
            if (line.startsWith('[error]')) {
                stderrLines.push('| ' + line.red);
            } else if (line.startsWith('[warn] ' + pathName)) {
                warnCnt++;
                stderrLines.push('| ' + line.blue);
            } else {
                stderrLines.push('| ' + line);
            }
            if (line.startsWith(pathName)) {
                successCnt++;
            }
        }
    });
    if (stderrLines.length > 0) {
        console.log("--------------------------------------------------------");
        console.log("| " + title);
        console.log("--------------------------------------------------------");
        console.log(stderrLines.join("\n"));
        console.log("========================================================");
        if (warnCnt > 0) {
            console.log("| Warn : " + (warnCnt + " cnt").blue);
            console.log("========================================================\n");
        }
        if (successCnt > 0) {
            console.log("| Success : " + (successCnt + " cnt").green);
            console.log("========================================================\n");
        }
    }
    return successCnt;
}

function runFormat(dirName, ext, checkType, callBack ) {
    // --check --write
    exec("npx prettier --"+checkType+" "+dirName+"/**/*." +ext, function(error, stdout, stderr) {
        if (stderr) {
            showValidString(stderr, 'Standard Error was occurred in ' + dirName.blue + '/**/*.' + ext, dirName );
        }
        let success = 0;
        if (stdout) {
            success = showValidString(stdout, 'Format success in ' + dirName.green + '/**/*.' + ext, dirName);
        }
        callBack(success);
    });
}

let totalSuccess = 0 ;
function runFormatProcess(dirName, extList, checkType, callBack ) {
    if (extList.length > 0) {
        const ext = extList.pop();
        runFormat(dirName, ext, checkType, function(success) {
            totalSuccess += success;
            runFormatProcess(dirName, extList, checkType, callBack);
        });
    } else {
        callBack(totalSuccess);
    }
}

function showLogo(callBack) {
    fs.readFile('./banner.txt', 'utf8', (error, jsonFile) => {
        const logo = jsonFile;
        fs.readFile('./package.json', 'utf8', (error, jsonFile) => {
            const packageInfo = JSON.parse(jsonFile);
            console.log(logo.blue + "\n" + (packageInfo.description +" " + packageInfo.version).red);
            callBack();
        });
    });
}
var myArgs = process.argv.slice(2);
showLogo(() => {
    if (myArgs.length > 0) {
        const folderName = myArgs[0];
        const question = [];
        question.push("Select Type of Format!!");
        question.push("html - "+folderName.red+"/**/*.html");
        question.push("ts - "+folderName.red+"/**/*.ts");
        question.push("scss - "+folderName.red+"/**/*.scss");
        question.push("css - "+folderName.red+"/**/*.css");
        question.push("json - "+folderName.red+"/**/*.json");
        question.push("java - "+folderName.red+"/**/*.java");
        question.push("vue - "+folderName.red+"/**/*.vue");
        question.push("xml - "+folderName.red+"/**/*.xml");
        question.push("check - just check");
        question.push("Format Types (html ts scss json java vue all check) - ? ");
        rl.question(question.join("\n"), function (formatType) {
            rl.close();
            const formatList = [];
            let checkType = 'write';
            if (formatType.indexOf('check') > -1) {
                checkType = 'check';
            }
            if (formatType === '') {
                formatType = 'all';
            }
            if (formatType.indexOf('all') > -1) {
                formatList.push('html');
                formatList.push('ts');
                formatList.push('js');
                formatList.push('vue');
                formatList.push('scss');
                formatList.push('css');
                formatList.push('json');
            } else {
                const formatTypeList = formatType.split(' ');
                formatTypeList.forEach(function(typeStr) {
                    switch(typeStr) {
                        case 'html' :
                        case 'ts' :
                        case 'scss' :
                        case 'css' :
                        case 'json' :
                        case 'vue' :
                        case 'xml' :
                        case 'java' :
                            if (formatList.indexOf(typeStr) === -1) {
                                formatList.push(typeStr);
                            }
                            break;
                    }
                });
            }
            if (formatList.length > 0) {
                runFormatProcess(folderName,formatList, checkType, function(cnt) {
                    console.log('Success Format '.green + ' - ' + (cnt + " cnt").red);
                });
            } else {
                console.log('missing argument!!'.red);
            }
        });
    } else {
        console.log('missing argument!!'.red);
    }
});