"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 });
exports.addTheming = addTheming;
const schematics_1 = require("@angular-devkit/schematics");
const schematics_2 = require("@angular/cdk/schematics");
const utility_1 = require("@schematics/angular/utility");
const calls_providers_function_1 = require("../utils/calls-providers-function");
const main_ts_file_path_1 = require("../utils/main-ts-file-path");
const workspace_1 = require("../utils/workspace");
/**
 * Add theming to angular.json and root module or config
 * @param options
 */
function addTheming(options) {
    return (tree, context) => __awaiter(this, void 0, void 0, function* () {
        if (options.theme === 'custom') {
            return;
        }
        context.logger.info(`⚠️ Currently, we don't automatically remove the deprecated Themes approach. If you have it applied you have to remove it by yourself.
[Instructions: https://sap.github.io/fundamental-ngx/#/core/theming]`);
        const buildTarget = yield (0, workspace_1.getProjectBuildTarget)(tree, options.project);
        const targetOptions = buildTarget.options;
        if (!targetOptions) {
            context.logger.info(`⚠️ Can not add theming to application. Please add theming manually. Reason: no target options found for project ${options.project}`);
            return;
        }
        const styles = targetOptions.styles;
        for (let i = 0; i < styles.length; i++) {
            const style = styles[i];
            const stylePath = typeof style === 'string' ? style : style.input;
            const baseVariablesMatch = stylePath.match(/@sap-theming\/(.*)\/baseLib\/(.*)\/css_variables.css$/);
            if (baseVariablesMatch) {
                const theme = baseVariablesMatch[2];
                context.logger
                    .info(`⚠️ Found theming ${theme} base SAP variables in styles. Can not add theme to application.
Try to replace theme in application manually, or use ThemingService to manage multiple themes.
[Instructions: https://sap.github.io/fundamental-ngx/#/core/theming]`);
                return;
            }
            const fundamentalStylesDeltaThemingVariablesMatch = stylePath.match(/fundamental-styles\/(.*)\/theming\/(.*)\/.css$/);
            if (fundamentalStylesDeltaThemingVariablesMatch) {
                const theme = fundamentalStylesDeltaThemingVariablesMatch[2];
                context.logger
                    .info(`⚠️ Found theming ${theme} fundamental-styles variables in styles. Can not add theme to application.
Try to replace theme in application manually, or use ThemingService to manage multiple themes.
[Instructions: https://sap.github.io/fundamental-ngx/#/core/theming]`);
                return;
            }
        }
        try {
            return (0, schematics_1.chain)([
                () => __awaiter(this, void 0, void 0, function* () {
                    if (!(yield (0, calls_providers_function_1.callsProvidersFunction)(tree, options.project, 'provideTheming'))) {
                        return (0, schematics_1.chain)([
                            (0, utility_1.addRootProvider)(options.project, ({ code, external }) => code `${external('provideTheming', '@fundamental-ngx/core/theming')}({ defaultTheme: '${options.theme}', changeThemeOnQueryParamChange: ${options.readThemeFromURL ? 'true' : 'false'} })`),
                            () => context.logger.info(`✅️ Added theming provider to root app config`)
                        ]);
                    }
                    context.logger.info(`✅️ Found theming provider in root app config, skipping adding it.`);
                }),
                () => __awaiter(this, void 0, void 0, function* () {
                    if (options.readThemeFromURL) {
                        const mainPath = yield (0, main_ts_file_path_1.getMainTsFilePath)(tree, options.project);
                        if ((0, schematics_2.isStandaloneApp)(tree, mainPath)) {
                            if (!(yield (0, calls_providers_function_1.callsProvidersFunction)(tree, options.project, 'provideRouter'))) {
                                return (0, schematics_1.chain)([
                                    (0, utility_1.addRootProvider)(options.project, ({ code, external }) => code `${external('provideRouter', '@fundamental-ngx/core/router')}([])`),
                                    () => context.logger.info(`✅️ Added router provider to root app config`)
                                ]);
                            }
                        }
                        else {
                            const appModulePath = (0, schematics_2.getAppModulePath)(tree, mainPath);
                            if (!(0, schematics_2.hasNgModuleImport)(tree, appModulePath, 'RouterModule')) {
                                (0, schematics_2.addModuleImportToRootModule)(tree, 'RouterModule.forRoot([])', '@angular/router', yield (0, workspace_1.getProjectDefinition)(tree, options.project));
                                context.logger.info(`✅️ Added RouterModule.forRoot([]) to root app module`);
                            }
                        }
                    }
                }),
                () => __awaiter(this, void 0, void 0, function* () {
                    if (!(yield (0, calls_providers_function_1.callsProvidersFunction)(tree, options.project, 'themingInitializer'))) {
                        return (0, schematics_1.chain)([
                            (0, utility_1.addRootProvider)(options.project, ({ code, external }) => code `${external('themingInitializer', '@fundamental-ngx/core/theming')}()`),
                            () => context.logger.info(`✅️ Added themingInitializer provider to root app config`)
                        ]);
                    }
                    context.logger.info(`✅️ Found themingInitializer provider in root app config, skipping adding it.`);
                })
            ]);
        }
        catch (e) {
            context.logger.debug(e);
            context.logger.info(`⚠️ Please process adding Theming to root module by yourself.
[Instructions: https://sap.github.io/fundamental-ngx/#/core/theming]`);
        }
    });
}
//# sourceMappingURL=index.js.map