"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 core_1 = require("@angular-devkit/core");
const ts = require("typescript");
const vendored_ast_utils_1 = require("../utils/vendored-ast-utils");
const workspace_1 = require("@schematics/angular/utility/workspace");
const schematics_1 = require("@angular/cdk/schematics");
const schematics_2 = require("@angular-devkit/schematics");
const gestures_1 = require("./gestures");
const fonts_1 = require("./fonts");
const styles_1 = require("../utils/styles");
const ast_1 = require("../utils/ast");
function updateAppModule(options) {
    return (host, _context) => __awaiter(this, void 0, void 0, function* () {
        _context.logger.debug('Updating appmodule');
        const workspace = yield workspace_1.getWorkspace(host);
        const project = schematics_1.getProjectFromWorkspace(workspace, options.project);
        const themes = options.themes.length ? options.themes : ['minima-light'];
        const theme = options.themes[0];
        const mainPath = schematics_1.getProjectMainFile(project);
        const modulePath = schematics_1.getAppModulePath(host, mainPath);
        _context.logger.debug(`module path: ${modulePath}`);
        // add import animations
        let moduleSource = getTsSourceFile(host, modulePath);
        let importModule = 'BrowserAnimationsModule';
        let importPath = '@angular/platform-browser/animations';
        if (!vendored_ast_utils_1.isImported(moduleSource, importModule, importPath)) {
            const change = vendored_ast_utils_1.insertImport(moduleSource, modulePath, importModule, importPath);
            if (change) {
                const recorder = host.beginUpdate(modulePath);
                recorder.insertLeft(change.pos, change.toAdd);
                host.commitUpdate(recorder);
            }
        }
        // register animations in app module
        moduleSource = getTsSourceFile(host, modulePath);
        let metadataChanges = schematics_1.addSymbolToNgModuleMetadata(moduleSource, modulePath, 'imports', importModule);
        if (metadataChanges) {
            const recorder = host.beginUpdate(modulePath);
            metadataChanges.forEach((change) => {
                recorder.insertRight(change.pos, change.toAdd);
            });
            host.commitUpdate(recorder);
        }
        // add import theme
        ['LyThemeModule', 'LY_THEME', 'LY_THEME_NAME'].forEach((_import) => {
            moduleSource = getTsSourceFile(host, modulePath);
            importModule = _import;
            importPath = '@alyle/ui';
            if (!vendored_ast_utils_1.isImported(moduleSource, importModule, importPath)) {
                const change = vendored_ast_utils_1.insertImport(moduleSource, modulePath, importModule, importPath);
                if (change) {
                    const recorder = host.beginUpdate(modulePath);
                    recorder.insertLeft(change.pos, change.toAdd);
                    host.commitUpdate(recorder);
                }
            }
        });
        // register theme in app module
        // const importText = `LyThemeModule.setTheme('${theme}')`;
        // moduleSource = getTsSourceFile(host, modulePath);
        // metadataChanges = addSymbolToNgModuleMetadata(
        //   moduleSource, modulePath, 'imports', importText);
        // if (!moduleSource.text.includes('LyThemeModule.setTheme') && metadataChanges) {
        //   const recorder = host.beginUpdate(modulePath);
        //   metadataChanges.forEach((change: InsertChange) => {
        //     recorder.insertRight(change.pos, change.toAdd);
        //   });
        //   host.commitUpdate(recorder);
        // }
        // register HammerModule in app module
        schematics_1.addModuleImportToModule(host, modulePath, 'HammerModule', '@angular/platform-browser');
        [
            'StyleRenderer',
            'LyTheme2'
        ].forEach(provider => {
            ast_1.addProvider(host, modulePath, 'NgModule', provider, '@alyle/ui');
        });
        // set theme
        moduleSource = getTsSourceFile(host, modulePath);
        const themeSimbolName = `{ provide: LY_THEME_NAME, useValue: '${theme}' }`;
        metadataChanges = schematics_1.addSymbolToNgModuleMetadata(moduleSource, modulePath, 'providers', themeSimbolName);
        if (metadataChanges) {
            const recorder = host.beginUpdate(modulePath);
            metadataChanges.forEach((change) => {
                recorder.insertRight(change.pos, change.toAdd);
            });
            host.commitUpdate(recorder);
        }
        themes.forEach(_themeName => {
            const [themePath] = _themeName.split('-');
            // register providers
            moduleSource = getTsSourceFile(host, modulePath);
            const simbolName = `{ provide: LY_THEME, useClass: ${core_1.strings.classify(_themeName)}, multi: true }`;
            metadataChanges = schematics_1.addSymbolToNgModuleMetadata(moduleSource, modulePath, 'providers', simbolName);
            if (metadataChanges) {
                const recorder = host.beginUpdate(modulePath);
                metadataChanges.forEach((change) => {
                    recorder.insertRight(change.pos, change.toAdd);
                });
                host.commitUpdate(recorder);
            }
            // add import themes
            moduleSource = getTsSourceFile(host, modulePath);
            importModule = core_1.strings.classify(_themeName);
            importPath = `@alyle/ui/themes/${themePath}`;
            if (!vendored_ast_utils_1.isImported(moduleSource, importModule, importPath)) {
                const change = vendored_ast_utils_1.insertImport(moduleSource, modulePath, importModule, importPath);
                if (change) {
                    const recorder = host.beginUpdate(modulePath);
                    recorder.insertLeft(change.pos, change.toAdd);
                    host.commitUpdate(recorder);
                }
            }
        });
    });
}
function getTsSourceFile(host, path) {
    const buffer = host.read(path);
    if (!buffer) {
        throw new schematics_2.SchematicsException(`Could not read file (${path}).`);
    }
    const content = buffer.toString();
    const source = ts.createSourceFile(path, content, ts.ScriptTarget.Latest, true);
    return source;
}
const STYLES = `\n\nconst STYLES = (theme: ThemeVariables, ref: ThemeRef) => {
  const __ = ref.selectorsOf(STYLES);
  return {
    $global: lyl \`{
      body {
        background-color: \${theme.background.default}
        color: \${theme.text.default}
        font-family: \${theme.typography.fontFamily}
        margin: 0
        direction: \${theme.direction}
      }
    }\`,
    root: lyl \`{
      display: block
    }\`
  };
};`;
function default_1(options) {
    return schematics_2.chain([
        gestures_1.addHammerJsToMain(options),
        updateAppModule(options),
        fonts_1.addFontsToIndex(options),
        styles_1.setUpStyles(options, undefined, undefined, STYLES),
    ]);
}
exports.default = default_1;
//# sourceMappingURL=setup-project.js.map