"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 path = require("path");
const PromptSession_1 = require("./../PromptSession");
let command;
// tslint:disable:object-literal-sort-keys
command = {
    command: "new [name]",
    desc: "creates a project",
    builder: {
        "name": {
            alias: "n",
            describe: "Project name",
            type: "string"
        },
        "framework": {
            alias: "f",
            default: "jquery",
            describe: "Framework to setup project for",
            type: "string",
            choices: []
        },
        "type": {
            alias: "t",
            describe: "Project type (depends on framework)",
            type: "string"
        },
        "theme": {
            alias: "th",
            describe: "Project theme (depends on project type)",
            type: "string"
        },
        "skip-git": {
            alias: "sg",
            describe: "Do not automatically initialize repository for the project with Git",
            type: "boolean"
        },
        "skip-install": {
            alias: "si",
            describe: "Do not automatically install packages",
            type: "boolean"
        },
        "template": {
            describe: "Project template",
            type: "string"
        }
    },
    template: null,
    execute(argv) {
        return __awaiter(this, void 0, void 0, function* () {
            cli_core_1.GoogleAnalytics.post({
                t: "screenview",
                cd: "New"
            });
            if (cli_core_1.ProjectConfig.hasLocalConfig()) {
                return cli_core_1.Util.error("There is already an existing project.", "red");
            }
            if (!argv.name) {
                const prompts = new PromptSession_1.PromptSession(command.template);
                yield prompts.start();
                return;
            }
            // trim
            argv.name = argv.name.trim();
            // letter+alphanumeric check
            if (!cli_core_1.Util.isAlphanumericExt(argv.name)) {
                cli_core_1.Util.error(`Name '${argv.name}' is not valid. `
                    + "Name should start with a letter and can also contain numbers, dashes and spaces.", "red");
                return;
            }
            if (cli_core_1.Util.directoryExists(argv.name)) {
                cli_core_1.Util.error(`Folder "${argv.name}" already exists!`, "red");
                return;
            }
            if (command.template.getFrameworkById(argv.framework) === undefined) {
                return cli_core_1.Util.error("Framework not supported", "red");
            }
            let projectLib;
            if (argv.type) {
                projectLib = command.template.getProjectLibrary(argv.framework, argv.type);
                if (!projectLib) {
                    return cli_core_1.Util.error(`Project type "${argv.type}" not found in framework '${argv.framework}'`);
                }
            }
            else {
                projectLib = command.template.getProjectLibrary(argv.framework);
            }
            if (command.template.getFrameworkById(argv.framework).id === "angular" && projectLib.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");
            }
            let themeIndex = 0;
            if (argv.theme) {
                themeIndex = projectLib.themes.findIndex(item => argv.theme.toLowerCase() === item.toLowerCase());
                if (themeIndex === -1) {
                    return cli_core_1.Util.error("Theme not supported");
                }
            }
            const theme = projectLib.themes[themeIndex];
            const indexOfEmptyOrFirst = projectLib.projectIds.indexOf("empty") !== -1
                ? projectLib.projectIds.indexOf("empty")
                : 0;
            const projectTemplate = argv.template || projectLib.projectIds[indexOfEmptyOrFirst];
            cli_core_1.Util.log(`Project Name: ${argv.name}, framework ${argv.framework}, type ${projectLib.projectType}, theme ${theme}`);
            const projTemplate = projectLib.getProject(projectTemplate);
            if (projTemplate == null) {
                return cli_core_1.Util.error("Project template not found");
            }
            // TODO: update output path based on where the CLI is called
            cli_core_1.GoogleAnalytics.post({
                t: "event",
                ec: "$ig new",
                ea: `project name: ${argv.name}; framework: ${projTemplate.framework}; ` +
                    `project type: ${projTemplate.projectType}; theme: ${theme}; skip-git: ${!!argv.skipGit}`,
                cd1: projTemplate.framework,
                cd2: projTemplate.projectType,
                cd3: argv.name,
                cd11: !!argv.skipGit,
                cd14: theme
            });
            const config = projTemplate.generateConfig(argv.name, theme);
            for (const templatePath of projTemplate.templatePaths) {
                yield cli_core_1.Util.processTemplates(templatePath, path.join(process.cwd(), argv.name), config, projTemplate.delimiters, false);
            }
            cli_core_1.Util.log(cli_core_1.Util.greenCheck() + " Project Created");
            if (!argv["skip-git"] && !cli_core_1.ProjectConfig.getConfig().skipGit) {
                cli_core_1.Util.gitInit(process.cwd(), argv.name);
            }
            if (!argv.skipInstall) {
                process.chdir(argv.name);
                yield cli_core_1.PackageManager.installPackages();
                process.chdir("..");
            }
            cli_core_1.Util.log("");
            cli_core_1.Util.log("Next Steps:");
            cli_core_1.Util.log(`  cd ${argv.name}`);
            cli_core_1.Util.log("  ig add      start guided mode for adding views to the app");
            cli_core_1.Util.log("  ig start    starts a web server and opens the app in the default browser");
        });
    }
};
exports.default = command;
