#!/usr/bin/env node
/**
 * Deploy compliled source ( dest -> was )
 *   
 * npm install --save-dev colors
 * npm install --save-dev iconv-lite
 */

'use strict';

require('colors');
const iconv = require('iconv-lite');
const fs = require('fs-extra');
const readline = require('readline');

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(iconv.decode(Buffer.from(stderrLines.join('\n'), 'utf-8'), 'euc-kr'));
        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;
}

var success = 0;
function runDepoly(dirName, extList, callBack) {
    if (extList.length > 0) {
        var ext = extList.shift();
        switch (ext) {
            case 'clear':
                fs.remove(dirName, function () {
                    fs.mkdir(dirName, function (aaa) {
                        runDepoly(dirName, extList, callBack);
                    });
                });
                break;
            case 'copy':
                fs.copy('dist/', dirName, function (err, aaa) {
                    fs.readFile(dirName + '/index.html', 'utf-8', function (err, buf) {
                        var contentsHtml = buf
                            .toString()
                            .replace(/\/mobile\/\.\//gi, '/mobile/')
                            .replace(/sgc\.mobile/g, 'SGC Mobile')
                            .replace(/SGC Mobile/g, 'SGC Mobile')
                            .replace(/manifest\.json/g, 'manifest.json?v=' + (new Date().getTime()))
                            .replace(/\t/g,'').split("\n").join('');
                        var contentsJsp = buf
                            .toString()
                            .replace(/\/mobile\/\.\//gi, '/mobile/')
                            .replace(/sgc\.mobile/g, '<%=(String)request.getAttribute("title")%>')
                            .replace(/SGC Mobile/g, '<%=(String)request.getAttribute("title")%>')
                            .replace(/manifest\.json/g, '<%=(String)request.getAttribute("manifest")%>?v=' + (new Date().getTime()))
                           // .replace(/manifest\.json/g, '<%=(String)request.getAttribute("manifest")%>')
                            .replace(/\t/g,'').split("\n").join('');
                            fs.writeFile(dirName + '/index.html', contentsHtml, 'utf-8', () => {
                                fs.writeFile(dirName + '/index.jsp', '<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>' +contentsJsp, 'utf-8', () => {
                                fs.readFile(dirName + '/firebase-messaging-sw.js', 'utf-8', function (err, buf) {
                                        var contents = buf.toString().replace(/\/img\//g, '/mobile/img/');
                                    fs.writeFile(dirName + '/../firebase-messaging-sw.js', contents, 'utf-8', () => {
                                        fs.readFile(dirName + '/manifest.json', 'utf-8', function (err, buf) {
                                            var contents = buf
                                                .toString()
                                                .replace(/\.\/img\//g, '/mobile/img/')
                                                .replace(/\/#/g, '/mobile/#')
                                            //    .replace(/\".\/\"/g, '/mobile/');
                                            fs.writeFile(
                                                dirName + '/../../resources/mobile-manifest.json',
                                                contents,
                                                'utf-8',
                                                () => {
                                                    runDepoly(dirName, extList, callBack);
                                                }
                                            );
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
                break;
            default:
                runDepoly(dirName, extList, callBack);
                break;
        }
    } else {
        callBack(success);
    }
}

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.red + "\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 Run!!');
        question.push('clear - ' + folderName.red + '/** will be remove');
        question.push('copy - ' + folderName.red + '/** wll be replaced by dist/**');
        question.push('     - ' + folderName + '/../' + 'firebase-messaging-sw.js'.red + ' wll be replaced.');
        question.push('     - ' + folderName + '/../../resources/' + 'mobile-manifest.json'.red + ' wll be replaced.');
        question.push('Run Type (clear, copy, all) - ? ');
        rl.question(question.join('\n'), function (formatType) {
            rl.close();
            const formatList = [];
            if (formatType === '') {
                formatList.push('clear');
                formatList.push('copy');
            } else if (formatType.indexOf('all') > -1) {
                formatList.push('clear');
                formatList.push('copy');
            } else {
                const formatTypeList = formatType.split(' ');
                formatTypeList.forEach(function (typeStr) {
                    switch (typeStr) {
                        case 'clear':
                        case 'copy':
                            if (formatList.indexOf(typeStr) === -1) {
                                formatList.push(typeStr);
                            }
                            break;
                    }
                });
            }
            if (formatList.length > 0) {
                formatList.push('end');
                runDepoly(folderName, formatList, function (cnt) {
                    console.log('Success Deploy '.green);
                    process.exit(1);
                });
            } else {
                console.log('missing argument!!'.red);
                process.exit(1);
            }
        });
    } else {
        console.log('missing argument!!'.red);
        process.exit(1);
    }
});
