"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const cli_core_1 = require("@igniteui/cli-core");
const PromptSession_1 = require("./../PromptSession");
let command;
// tslint:disable:object-literal-sort-keys
command = {
    command: "add [template] [name]",
    desc: "adds template by its ID",
    templateManager: null,
    builder: {
        "template": {
            alias: "t",
            description: `Template ID, such as "grid", "combo", etc.`,
            type: "string",
            global: true
        },
        "name": {
            alias: "n",
            description: "File name.",
            type: "string",
            global: true
        },
        "module": {
            alias: "m",
            description: "The module to which the template is to be added",
            type: "string",
            global: true
        },
        "skip-route": {
            alias: "skr",
            describe: "Don't auto-generate an app navigation route for the new component",
            type: "boolean",
            global: true
        }
    },
    check: argv => {
        if ((!argv.name && argv.template) || (argv.name && !argv.template)) {
            return false;
        }
        return true;
    },
    execute(argv) {
        return __awaiter(this, void 0, void 0, function* () {
            cli_core_1.GoogleAnalytics.post({
                t: "screenview",
                cd: "Add"
            });
            if (!cli_core_1.ProjectConfig.hasLocalConfig()) {
                cli_core_1.Util.error("Add command is supported only on existing project created with igniteui-cli", "red");
                return;
            }
            const config = cli_core_1.ProjectConfig.getConfig();
            if (config.project.isShowcase) {
                cli_core_1.Util.error("Showcases and quickstart projects don't support the add command", "red");
                return;
            }
            const framework = command.templateManager.getFrameworkById(config.project.framework);
            if (!framework) {
                cli_core_1.Util.error("Framework not supported", "red");
                return;
            }
            const frameworkLibrary = command.templateManager.getProjectLibrary(config.project.framework, config.project.projectType);
            if (!argv.template && !argv.name) {
                const prompts = new PromptSession_1.PromptSession(command.templateManager);
                yield prompts.chooseActionLoop(frameworkLibrary);
                return;
            }
            if (!frameworkLibrary.hasTemplate(argv.template)) {
                cli_core_1.Util.error("Template doesn't exist in the current library", "red");
                return;
            }
            if (framework.id === "angular" && frameworkLibrary.projectType === "igx-ts") {
                cli_core_1.Util.warn("Psst! Did you know you can use our schematics package with Angular CLI to create and modify your projects?", "yellow");
                cli_core_1.Util.warn("Read more at: https://www.infragistics.com/products/ignite-ui-angular/angular/components/general/cli-overview", "yellow");
            }
            const selectedTemplate = frameworkLibrary.getTemplateById(argv.template);
            if (selectedTemplate) {
                cli_core_1.GoogleAnalytics.post({
                    t: "event",
                    ec: "$ig add",
                    ea: `template id: ${argv.template}; file name: ${argv.name}`,
                    cd1: selectedTemplate.framework,
                    cd2: selectedTemplate.projectType,
                    cd5: selectedTemplate.controlGroup,
                    cd7: selectedTemplate.id,
                    cd8: selectedTemplate.name,
                    cd11: !!config.skipGit,
                    cd14: config.project.theme
                });
                yield command.addTemplate(argv.name, selectedTemplate, {
                    modulePath: argv.module,
                    skipRoute: argv.skipRoute
                });
                yield cli_core_1.PackageManager.flushQueue(true);
                yield cli_core_1.PackageManager.ensureIgniteUISource(config.packagesInstalled, command.templateManager);
            }
        });
    },
    addTemplate(fileName, template, options) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!options) {
                if (template.framework === "react") {
                    options = {
                        parentName: "app",
                        className: cli_core_1.Util.className(fileName),
                        modulePath: `src/app/${cli_core_1.Util.lowerDashed(fileName)}`
                    };
                    options["parentRoutingModulePath"] = template.projectType === "igr-ts"
                        ? "src/app/app-routes.tsx"
                        : "./src/routes.json";
                }
                else {
                    options = {
                        parentName: "app",
                        parentRoutingModulePath: "src/app/app-routing.ts",
                        selector: "app-" + template.id
                    };
                }
            }
            fileName = fileName.trim();
            const name = cli_core_1.Util.nameFromPath(fileName);
            // letter+alphanumeric check
            if (!cli_core_1.Util.isAlphanumericExt(name)) {
                cli_core_1.Util.error(`Name '${name}' is not valid. `
                    + "Name should start with a letter and can also contain numbers, dashes and spaces.", "red");
                return false;
            }
            const config = template.generateConfig(fileName, options || {});
            let fail = false;
            const templatePaths = template.templatePaths;
            for (const templatePath of templatePaths) {
                fail = fail || !(yield cli_core_1.Util.processTemplates(templatePath, process.cwd(), config, template.delimiters));
            }
            if (!fail && templatePaths.length) {
                template.registerInProject(process.cwd(), fileName, options || {});
                command.templateManager.updateProjectConfiguration(template);
                template.packages.forEach(x => cli_core_1.PackageManager.queuePackage(x));
                cli_core_1.Util.log(`${cli_core_1.Util.greenCheck()} View '${name}' added.`);
                return true;
            }
            else {
                /* Log error? */
                return false;
            }
        });
    }
};
// hint transpiler it's an ES6 module, exports without import won't do
exports.default = command;
