#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var fs = require("fs-extra");
var child_process = require("child_process");
var glob = require("glob");
var path = require("path");
var yaml = require("js-yaml");
var program = require("commander");
var src;
var repoRelativePath;
var dest = 'docs-ref-autogen';
var packageWhiteList = [];
var packageBlackList = [];
var config;
var pjson = require('../package.json');
var envPath = process.env['APPDATA'] + "/npm/node_modules/ts-reference-ci-scripts";
program
    .version("v" + pjson.version)
    .description('A tool to go through source code and convert it to yaml data model for docfx.')
    .option('--config [value]', 'The config file which will defined more specefied behaviour for the tool')
    .option('--whiteList [value]', 'White list some package name for extraction.')
    .option('--blackList [value]', 'Black list some package name for extraction. Black list will override whitelist.')
    .option('--destPath [value]', 'Path to output the autogen files.')
    .arguments('<sourceFolder> [repoConfigPath]')
    .action(function (sourceFolder, repoConfig) {
    src = sourceFolder;
    repoRelativePath = repoConfig;
})
    .parse(process.argv);
if (!src) {
    console.log('Error: The source file folder is not specified!');
    program.help();
}
if (program.config) {
    try {
        config = JSON.parse(program.config);
    }
    catch (e) {
        console.log("Invalid json format of config, ignored! content: " + program.config);
    }
}
if (program.whiteList) {
    try {
        var tempList = JSON.parse(program.whiteList);
        if (tempList && tempList.length) {
            packageWhiteList = tempList;
        }
    }
    catch (e) {
        console.log('Invalid json format of white list, ignored!');
    }
}
if (program.blackList) {
    try {
        var tempList = JSON.parse(program.blackList);
        if (tempList && tempList.length) {
            packageBlackList = tempList;
        }
    }
    catch (e) {
        console.log('Invalid json format of black list, ignored!');
    }
}
if (config && config.package_white_list) {
    packageWhiteList = config.package_white_list;
}
if (config && config.package_black_list) {
    packageBlackList = config.package_black_list;
}
if (program.destPath) {
    if (config.target_repo.folder) {
        dest = program.destPath + "/" + config.target_repo.folder + "/" + dest;
    }
    else {
        dest = program.destPath + "/" + dest;
    }
}
// 1. prepare
fs.removeSync(dest);
fs.mkdirpSync(dest);
var packagePaths = glob.sync(path.join(src, '**/package.json'));
var toc = [];
packagePaths.forEach(function (packagePath) {
    generatePackageDoc(packagePath, dest);
});
toc = JSON.parse(JSON.stringify(toc));
fs.writeFileSync(dest + "/toc.yml", yaml.safeDump(toc));
process.exit(0);
function generatePackageDoc(packagePath, dest) {
    var dir = path.dirname(packagePath);
    if (!fs.existsSync(packagePath)) {
        return;
    }
    var packageName = fs.readJsonSync(packagePath).name;
    if (packageWhiteList.length === 0 || packageWhiteList.indexOf(packageName) >= 0) {
        if (packageBlackList.indexOf(packageName) >= 0) {
            return;
        }
        console.log(packageName);
        console.log(dir);
        var sourceCodeBasePath = dir + "/src";
        var folder = dir.split('/')[1];
        var processed = false;
        var folderIndex = parseInt(folder, 10);
        if (folderIndex !== NaN && config.source_repos[folderIndex] && config.source_repos[folderIndex].folder) {
            sourceCodeBasePath = dir + "/" + config.source_repos[folderIndex].folder;
        }
        if (fs.existsSync(sourceCodeBasePath)) {
            var packageDest = dest + "/" + packageName;
            fs.mkdirpSync(packageDest);
            try {
                child_process.execSync("typedoc --json " + dir + "/api.json " + sourceCodeBasePath + " --module commonjs --includeDeclarations --ignoreCompilerErrors");
                var basePath = sourceCodeBasePath.replace(src + "/", '');
                var extraCommand = getExtraCommand(config);
                if (config && config.source_repo) {
                    child_process.execSync("type2docfx " + dir + "/api.json " + packageDest + " --sourceUrl " + config.source_repo.url + " --sourceBranch " + config.source_repo.branch + " --basePath " + basePath + " " + extraCommand);
                }
                else if (config && config.source_repos) {
                    var processed_1 = false;
                    if (folderIndex !== NaN && config.source_repos[folderIndex]) {
                        basePath = basePath.replace(folder + "/", '');
                        child_process.execSync("type2docfx " + dir + "/api.json " + packageDest + " --sourceUrl " + config.source_repos[folderIndex].url + " --sourceBranch " + config.source_repos[folderIndex].branch + " --basePath " + basePath + " " + extraCommand);
                        processed_1 = true;
                    }
                    else if (folder) {
                        for (var index in config.source_repos) {
                            if (folder === config.source_repos[index].folder) {
                                basePath = basePath.replace(folder + "/", '');
                                child_process.execSync("type2docfx " + dir + "/api.json " + packageDest + " --sourceUrl " + config.source_repos[index].url + " --sourceBranch " + config.source_repos[index].branch + " --basePath " + basePath + " " + extraCommand);
                                processed_1 = true;
                                break;
                            }
                        }
                    }
                    if (!processed_1) {
                        child_process.execSync("type2docfx " + dir + "/api.json " + packageDest + " --sourceUrl " + config.source_repos[0].url + " --sourceBranch " + config.source_repos[0].branch + " --basePath " + basePath + " " + extraCommand);
                    }
                }
                else {
                    child_process.execSync("type2docfx " + dir + "/api.json " + packageDest + " " + extraCommand);
                }
                if (fs.existsSync(packageDest + "/toc.yml")) {
                    var subToc = yaml.safeLoad(fs.readFileSync(packageDest + "/toc.yml").toString());
                    toc.push(subToc[0]);
                    fs.removeSync(packageDest + "/toc.yml");
                }
            }
            catch (e) {
                console.log(packageName + ": TypeDoc Parse Error.");
            }
        }
        else {
            console.log("No source file for " + packageName);
        }
    }
}
function getExtraCommand(config) {
    var extraCommand = '';
    if (config.has_module) {
        extraCommand += ' --hasModule';
    }
    if (config.disable_alphabet_order) {
        extraCommand += ' --disableAlphabetOrder';
    }
    if (config.enable_function_level_toc) {
        extraCommand += ' --enableFunctionLevelToc';
    }
    return extraCommand;
}
