"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const strings_1 = require("@angular-devkit/core/src/utils/strings");
const schematics_1 = require("@angular-devkit/schematics");
const lib_1 = require("../../lib");
const angular_utility_1 = require("../../lib/angular-utility");
const app_page_render_engine_1 = require("../app-page-render-engine");
function hasAnonymousProfile(schema) {
    if (!schema.config.data || !schema.config.data.profiles)
        return false;
    return Boolean(schema.config.data.profiles.find(data => data.username === 'anonymous'));
}
function default_1(_options) {
    return schematics_1.chain([
        (tree, context) => {
            var _a;
            const project = lib_1.loadProject(tree, context);
            const tapConfig = project.tapConfig;
            let libName;
            const parentPage = "TapDevicePage";
            const monitoringPage = project.appConfigBuilder.monitoringPage(_options.name);
            if (monitoringPage.enabled) {
                project.save();
                const relativePath = monitoringPage.projectPath;
                if (_options.library) {
                    const appName = _options.name || `${((_a = tapConfig.config.application) === null || _a === void 0 ? void 0 : _a.name) || 'TAP'}-lib`;
                    libName = `${strings_1.dasherize(appName)}`;
                }
                if (!tapConfig.config.data) {
                    context.logger.error(`Tap configuration does not contain any data. Monitoring cannot be generated`);
                    return;
                }
                if (!tapConfig.config.data.profiles) {
                    context.logger.error(`Tap configuration does not contain any profile. Monitoring cannot be generated`);
                    return;
                }
                if (!tapConfig.config.data.bundles || tapConfig.config.data.bundles.length === 0) {
                    context.logger.error(`Tap configuration does not contain any bundles. Monitoring cannot be generated`);
                    return;
                }
                if (!hasAnonymousProfile(tapConfig)) {
                    console.warn(`Anonymous profile is not present in configuration `);
                    lib_1.updateTapConfig(tree, (schema) => {
                        const anonymousProfile = {
                            username: 'anonymous',
                            id: 0,
                            lifeTime: 0
                        };
                        schema.config.data.profiles.push(anonymousProfile);
                        tapConfig.config.data.profiles.push(anonymousProfile);
                        return schema;
                    });
                }
                const { name, path } = lib_1.getAngularProjectPath(relativePath, tree, {
                    project: libName
                });
                if (!project.appConfigSchema.app.defaultPage) {
                    project.appConfigSchema.app.defaultPage = monitoringPage.path;
                }
                const dashboardPages = monitoringPage.children || [];
                const dashboardRules = dashboardPages.map((dashboard) => {
                    const generateDashboardOptions = {
                        profile: dashboard.profileName,
                        overwrite: _options.overwrite,
                        reconfigure: false
                    };
                    return schematics_1.schematic('page-monitoring-dashboard', generateDashboardOptions);
                });
                if (dashboardRules.length == 0) {
                    throw new Error(`Cannot generate monitoring page if no profile have been defined in configuration`);
                }
                const tapDataManagerOptions = {
                    project: libName,
                    name: `${relativePath}/tap-api`
                };
                const libraryOptions = {
                    name: libName,
                    skipInstall: true // Todo as argument
                };
                return schematics_1.chain([
                    (_options.library && _options.overwrite) ? schematics_1.schematic('rm-project', {
                        project: libName
                    }) : schematics_1.noop(),
                    _options.library ? schematics_1.externalSchematic("@schematics/angular", 'library', libraryOptions) : schematics_1.noop(),
                    schematics_1.schematic('tap-data-manager', tapDataManagerOptions),
                    ...dashboardRules,
                    (tree, _) => {
                        const routingScope = 'Child';
                        const sourceTemplates = schematics_1.url(app_page_render_engine_1.PageRenderEngine.getTemplatePath('MonitoringPage'));
                        const dashboards = monitoringPage.children || [];
                        const routes = project.createRoutesForPages(monitoringPage, dashboards, (dashboardPage) => {
                            return {
                                profileName: dashboardPage.profileName !== 'anonymous' ? dashboardPage.profileName : undefined
                            };
                        });
                        const anonymousDasboard = dashboards.find(dashboard => dashboard.profileName === 'anonymous');
                        const defaultMonitoringPage = anonymousDasboard ? anonymousDasboard.path : routes.length > 0 ? routes[0].path : undefined;
                        if (defaultMonitoringPage) {
                            routes.push({
                                path: '',
                                redirectTo: defaultMonitoringPage,
                                pathMatch: 'full'
                            });
                        }
                        return angular_utility_1.applyWithOverwriteRule(sourceTemplates, [
                            schematics_1.template(Object.assign({ routingScope,
                                routes,
                                name, 
                                // commonModule: false,
                                routing: true }, project.toTemplate())),
                            schematics_1.move(path)
                        ], {
                            overwrite: _options.overwrite,
                            format: true
                        });
                    },
                    (tree, _) => {
                        const project = lib_1.loadProject(tree, context);
                        project.appConfigBuilder.addMenuForSubPage(monitoringPage, 'analytics', parentPage);
                        project.save();
                    },
                    ...dashboardRules
                ]);
            }
        }
    ]);
}
exports.default = default_1;
//# sourceMappingURL=index.js.map