"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IgniteUIForReactTemplate = void 0;
const cli_core_1 = require("@igniteui/cli-core");
const fs = require("fs-extra");
const path = require("path");
const ReactTypeScriptFileUpdate_1 = require("../../templates/react/ReactTypeScriptFileUpdate");
const typescript_1 = require("typescript");
class IgniteUIForReactTemplate {
    /**
     * Base ReactTemplate constructor
     * @param rootPath The template folder path. Pass in `__dirname`
     */
    constructor(rootPath) {
        this.rootPath = rootPath;
        this.listInComponentTemplates = true;
        this.listInCustomTemplates = false;
        this.dependencies = [];
        this.framework = "react";
        this.hasExtraConfiguration = false;
        this.packages = [];
        this.delimiters = cli_core_1.defaultDelimiters;
    }
    get templatePaths() {
        return [path.join(this.rootPath, "files")];
    }
    generateConfig(name, options) {
        let config = {};
        if (options["extraConfig"]) {
            config = options["extraConfig"];
        }
        config["path"] = this.folderName(name); //folder name allowed spaces, any casing
        config["name"] = cli_core_1.Util.nameFromPath(name); // this name should not have restrictions
        config["ClassName"] = cli_core_1.Util.className(cli_core_1.Util.nameFromPath(name)); //first letter capital, no spaces and no dashes,
        config["filePrefix"] = cli_core_1.Util.lowerDashed(cli_core_1.Util.nameFromPath(name));
        config["cliVersion"] = cli_core_1.Util.version();
        if (this.widget) {
            config["widget"] = this.widget;
            config["Control"] = cli_core_1.Util.className(this.widget);
        }
        if (this.description) {
            config["description"] = this.description;
        }
        return config;
    }
    registerInProject(projectPath, name, options, defaultPath = false) {
        if (!options.parentName) {
            return;
        }
        if (this.projectType === "igr-es6") {
            this.registerJSONRoute(projectPath, name, options.parentRoutingModulePath);
            return;
        }
        const routeModulePath = options.parentRoutingModulePath;
        if (!(options && options.skipRoute)
            && cli_core_1.App.container.get(cli_core_1.FS_TOKEN).fileExists(routeModulePath)) {
            const routingModule = new ReactTypeScriptFileUpdate_1.ReactTypeScriptFileUpdate(path.join(projectPath, routeModulePath), { convertTabsToSpaces: false, indentSize: 4, singleQuotes: true }, { jsx: typescript_1.JsxEmit.Preserve });
            const modulePath = `./${cli_core_1.Util.lowerDashed(name)}/${cli_core_1.Util.lowerDashed(name)}-routes`;
            const child = {
                identifierName: cli_core_1.ROUTES_VARIABLE_NAME,
                aliasName: options.routerChildren,
                modulePath
            };
            if (defaultPath) {
                routingModule.addRoute({
                    index: true,
                    redirectTo: options.path,
                });
            }
            const children = routeModulePath.includes(cli_core_1.REACT_APP_ROUTING_NAME)
                ? child
                : undefined;
            if (options.hasChildren) {
                routingModule.addRoute({
                    path: this.fileName(name),
                    element: cli_core_1.Util.className(name),
                    text: cli_core_1.Util.nameFromPath(name),
                    children
                });
            }
            else {
                routingModule.addRoute({
                    path: this.fileName(name),
                    element: cli_core_1.Util.className(name),
                    text: cli_core_1.Util.nameFromPath(name)
                }, false, // multiline
                false // prepend
                );
            }
            routingModule.finalize();
        }
    }
    getExtraConfiguration() {
        throw new Error("Method not implemented.");
    }
    setExtraConfiguration(extraConfigKeys) {
        throw new Error("Method not implemented.");
    }
    folderName(pathName) {
        //TODO: should remove the spaces
        const parts = path.parse(pathName);
        let folderName = pathName;
        if (parts.dir) {
            folderName = path.join(parts.dir, parts.name);
            folderName = folderName.replace(/\\/g, "/");
            // TODO: config-based "src/app"?
            const relative = path.join(process.cwd(), "src/views", folderName);
            // path.join will also resolve any '..' segments
            // so if relative result doesn't start with CWD it's out of project root
            if (!relative.startsWith(process.cwd())) {
                cli_core_1.Util.error(`Path ${"src/views/" + folderName} is not valid!`, "red");
                process.exit(1);
            }
            //clean up potential leading spaces in folder names (`path/ name`):
            folderName = folderName.replace(/\/\s+/g, "/");
        }
        return cli_core_1.Util.lowerDashed(folderName);
    }
    fileName(pathName) {
        const name = cli_core_1.Util.nameFromPath(pathName);
        return cli_core_1.Util.lowerDashed(name);
    }
    registerJSONRoute(projectPath, name, routingModulePath) {
        const configFile = fs.readFileSync(path.join(projectPath, routingModulePath), "utf8");
        const viewsArr = JSON.parse(configFile);
        viewsArr.push({
            componentPath: this.getViewLink(name),
            path: "/" + this.folderName(cli_core_1.Util.nameFromPath(name)),
            text: this.getToolbarLink(name)
        });
        fs.writeFileSync(path.join(projectPath, routingModulePath), JSON.stringify(viewsArr, null, 4));
    }
    getViewLink(name) {
        const filePath = "./views/" + this.folderName(name);
        return filePath;
    }
    getToolbarLink(name) {
        name = cli_core_1.Util.nameFromPath(name);
        const toolbarLink = name.replace(/\w\S*/g, txt => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());
        return toolbarLink;
    }
}
exports.IgniteUIForReactTemplate = IgniteUIForReactTemplate;
