"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HomePageService = void 0;
const tslib_1 = require("tslib");
const core_1 = require("@loopback/core");
const countries_list_1 = require("countries-list");
const jsdom_1 = require("jsdom");
const path_1 = tslib_1.__importDefault(require("path"));
const generated_response_1 = require("../../helper/generated-response");
const models_1 = require("../../models");
const services_1 = require("../../services");
const application_error_1 = require("./../../helper/application-error");
const generated_response_2 = require("./../../helper/generated-response");
const locales_helper_1 = require("./../../helper/locales-helper");
const action_entity_service_1 = require("./../../services/action-entity/action-entity.service");
const application_service_1 = require("./../../services/application.service");
const content_entity_service_1 = require("./../../services/content-entity/content-entity.service");
const node_intercept_service_1 = require("./../../services/entity-intercept/node-intercept.service");
const inside_rest_service_1 = require("./../../services/inside-rest/inside-rest.service");
const object_node_service_1 = require("./../../services/object-node/object-node.service");
const object_tree_const_1 = require("./../../services/object-tree/object-tree.const");
const object_tree_service_1 = require("./../../services/object-tree/object-tree.service");
const object_type_service_1 = require("./../../services/object-type.service");
const transient_entity_service_1 = require("./../../services/transient-entity/transient-entity.service");
const travel_story_type_const_1 = require("./../travel-story/travel-story-type.const");
const action_web_site_service_1 = require("./../web-site/action-web-site.service");
const web_site_const_1 = require("./../web-site/web-site.const");
const home_page_const_1 = require("./home-page.const");
let HomePageService = class HomePageService {
    constructor(actionWebSiteService, objectTreeService, objectNodeService, objectTypeService, nodeInterceptService, contentEntityService, applicationService, actionEntityService, transientEntityService, insideRestService) {
        this.actionWebSiteService = actionWebSiteService;
        this.objectTreeService = objectTreeService;
        this.objectNodeService = objectNodeService;
        this.objectTypeService = objectTypeService;
        this.nodeInterceptService = nodeInterceptService;
        this.contentEntityService = contentEntityService;
        this.applicationService = applicationService;
        this.actionEntityService = actionEntityService;
        this.transientEntityService = transientEntityService;
        this.insideRestService = insideRestService;
        this.nodeInterceptService.registerEntityInterceptorService(home_page_const_1.HOME_PAGE_PROVIDER, HomePageService.name, 'Calculate name from host and path', home_page_const_1.WEB_SITE_VIEW_URL_TYPE.name, application_service_1.EntityActionType.create, this.interceptWebSiteViewUrlCreate.bind(this));
        this.nodeInterceptService.registerEntityInterceptorService(home_page_const_1.HOME_PAGE_PROVIDER, HomePageService.name, 'Calculate name from host and path', home_page_const_1.WEB_SITE_VIEW_URL_TYPE.name, application_service_1.EntityActionType.update, this.interceptWebSiteViewUrlUpdate.bind(this));
        this.actionEntityService.registerNewMethodFunction(home_page_const_1.HOME_PAGE_PROVIDER, HomePageService.name, 'Publish web site', models_1.EntityName.objectNode, 'publish', home_page_const_1.WEB_SITE_VIEW_URL_TYPE.name, this.publishSite.bind(this), 'delete');
        this.transientEntityService.registerTransientEntityTypeFunction(home_page_const_1.HOME_PAGE_PROVIDER, HomePageService.name, 'Add publish method definition to publish site for a locale', models_1.EntityName.objectNode, home_page_const_1.WEB_SITE_VIEW_URL_TYPE.name, this.completeWebSiteCacheLangTypeNode.bind(this));
        this.actionEntityService.registerNewViewFunction(home_page_const_1.HOME_PAGE_PROVIDER, HomePageService.name, 'Get site map', models_1.EntityName.objectTree, 'sitemap', home_page_const_1.WEB_SITE_CACHE_LANG_TYPE.name, this.getSiteMap.bind(this), services_1.AccessRightsScope.read, {
            transientEntityService: this.transientEntityService,
            icon: 'fas fa-sitemap',
            viewName: 'View Site Map',
        });
        this.actionEntityService.registerNewViewFunction(home_page_const_1.HOME_PAGE_PROVIDER, HomePageService.name, 'Preview site map', models_1.EntityName.objectTree, 'sitemap', web_site_const_1.WEB_SITE_VIEW_TYPE.name, this.previewWebSite.bind(this), services_1.AccessRightsScope.read, {
            transientEntityService: this.transientEntityService,
            icon: 'fas fa-sitemap',
            viewName: 'Preview Site Map',
        });
    }
    async getSiteUrls(webSiteId, includePopupUrls = false) {
        const urls = [];
        const pageTypeIds = await this.objectTypeService.getImplementingTypes(web_site_const_1.PAGE_TYPE.name);
        // TO DO : list PAGE_TYPE.name
        const pages = await this.objectNodeService.searchByParentTreeId(webSiteId, { objectTypeIds: pageTypeIds });
        for (const page of pages) {
            if (page.pageTitle) {
                urls.push('/' + page.name);
            }
        }
        if (includePopupUrls) {
            for (const page of pages) {
                urls.push('/' + page.name + '/popup');
            }
        }
        return urls;
    }
    async completeWebSiteCacheLangTypeNode(objectNode, ctx) {
        var _a;
        const urls = await this.getSiteUrls(objectNode.parentTreeId, true);
        if (!objectNode.entityCtx) {
            objectNode.entityCtx = { entityType: models_1.EntityName.objectNode };
        }
        if (!((_a = objectNode.entityCtx) === null || _a === void 0 ? void 0 : _a.actions)) {
            objectNode.entityCtx.actions = {};
        }
        if (!objectNode.entityCtx.actions.methods) {
            objectNode.entityCtx.actions.methods = [];
        }
        objectNode.entityCtx.actions.methods.push({
            methodId: 'publish',
            methodName: 'Publish site',
            actionName: 'Publish site',
            parameters: {
                type: 'object',
                properties: {
                    locale: {
                        type: 'string',
                        title: 'Language',
                        required: true,
                        oneOf: [
                        /*
                      {"enum": ["none"], "title": "never"},
                      */
                        ],
                    },
                },
                icon: 'fas fa-globe-europe',
            },
            handlebarsMethodSampling: `[
          {
            "methodId": "publish",
            "parameters":{
              "init":"true",
              "url":"",
              "locale":"{{locale}}"
            }
          }`,
        });
        for (const url of urls) {
            objectNode.entityCtx.actions.methods[objectNode.entityCtx.actions.methods.length - 1].handlebarsMethodSampling += `,
        {
          "methodId": "publish",
          "parameters":{
            "url":"${url}",
            "locale":"{{locale}}"
          }
        }`;
        }
        objectNode.entityCtx.actions.methods[objectNode.entityCtx.actions.methods.length - 1].handlebarsMethodSampling += ']';
        const localesChildren = await this.objectNodeService.getOrCreateChildren(objectNode.id, home_page_const_1.WEB_SITE_CACHE_LANG_TYPE.name);
        if ((localesChildren === null || localesChildren === void 0 ? void 0 : localesChildren.length) > 0) {
            const allKey = localesChildren.map((child) => child.name).join(',');
            objectNode.entityCtx.actions.methods[objectNode.entityCtx.actions.methods.length - 1].parameters.properties.locale.oneOf.push({
                enum: [allKey],
                title: 'Already published countries',
            });
            objectNode.entityCtx.actions.methods[objectNode.entityCtx.actions.methods.length - 1].parameters.properties.locale.default = allKey;
            for (const child of localesChildren) {
                const localParts = child.name.split('-');
                if (2 === localParts.length &&
                    localParts[0] in countries_list_1.languagesAll &&
                    localParts[1] in countries_list_1.countries) {
                    objectNode.entityCtx.actions.methods[objectNode.entityCtx.actions.methods.length - 1].parameters.properties.locale.oneOf.push({
                        enum: [child.name],
                        title: countries_list_1.countries[localParts[1]].name +
                            ', ' +
                            countries_list_1.languagesAll[localParts[0]].name,
                    });
                }
            }
        }
        for (const country in countries_list_1.countries) {
            for (const lang of countries_list_1.countries[country]
                .languages) {
                objectNode.entityCtx.actions.methods[objectNode.entityCtx.actions.methods.length - 1].parameters.properties.locale.oneOf.push({
                    enum: [lang + '-' + country],
                    title: countries_list_1.countries[country].name +
                        ', ' +
                        countries_list_1.languagesAll[lang].name,
                });
            }
        }
    }
    async publishSite(objectNode, _args, ctx) {
        const args = _args;
        const locales = args.locale.split(',');
        if (args.init) {
            const localesChildren = await this.objectNodeService.getOrCreateChildren(objectNode.id, home_page_const_1.WEB_SITE_CACHE_LANG_TYPE.name);
            for (const child of localesChildren) {
                if (-1 < locales.indexOf(child.name)) {
                    await this.objectNodeService.removeById(child.id, services_1.CurrentContext.get(ctx));
                }
            }
        }
        for (const locale of locales) {
            await this.publishSiteLang(objectNode, locale, args.url, ctx);
        }
        return this.actionEntityService.getEntity(models_1.EntityName.objectTree, objectNode.id, services_1.CurrentContext.get(ctx, {}));
    }
    async publishSiteLang(objectNode, lang, url, ctx) {
        // TO DO : get WebSite or build the URL ?
        let webSiteUrl = `http://${objectNode.host}`;
        if (objectNode.path) {
            webSiteUrl += `/site/${objectNode.path}`;
        }
        webSiteUrl += '/' + lang;
        await this.insideRestService.read(webSiteUrl + url, ctx);
    }
    async interceptWebSiteViewUrlCreate(entityId, entity, requestEntity, ctx) {
        if (requestEntity.name) {
            delete requestEntity.name;
        }
        if (requestEntity.title) {
            delete requestEntity.title;
        }
        const host = !!requestEntity.host && '' !== requestEntity.host
            ? requestEntity.host
            : false;
        if (!host) {
            return false;
        }
        requestEntity.title =
            'http://' +
                host +
                (requestEntity.path ? '/site/' + requestEntity.path : '');
        requestEntity.path = requestEntity.path ? requestEntity.path : '';
        requestEntity.name = host + '$' + requestEntity.path;
        return true;
    }
    async interceptWebSiteViewUrlUpdate(entityId, entity, requestEntity, ctx) {
        if (requestEntity.name) {
            delete requestEntity.name;
        }
        if (requestEntity.title) {
            delete requestEntity.title;
        }
        requestEntity.host =
            !!requestEntity.host && '' !== requestEntity.host
                ? requestEntity.host
                : entity.host;
        if (!requestEntity.host) {
            return false;
        }
        requestEntity.title =
            'http://' +
                requestEntity.host +
                (requestEntity.path ? '/site/' + requestEntity.path : '');
        requestEntity.path = requestEntity.path
            ? requestEntity.path
            : entity.path
                ? entity.path
                : '';
        requestEntity.name = requestEntity.host + '$' + requestEntity.path;
        return true;
    }
    async lookWebSiteEntry(subPath, ctx) {
        return ctx.webSiteContext.urlNode.getOrSetValue(async () => {
            const host = ctx.uriContext.uri.value.host;
            subPath = subPath ? subPath : '';
            const uri = await this.objectNodeService.searchOwner(home_page_const_1.WEB_SITE_VIEW_URL_TYPE.name, host + '$' + subPath);
            if (!uri) {
                throw application_error_1.ApplicationError.notFound({ host, subPath });
            }
            return uri;
        });
    }
    initLangAndUser(lang, ctx) {
        if ('explorer' === lang &&
            ctx.uriContext.uri.value.baseUri.endsWith('/api')) {
            return new generated_response_2.RedirectGeneratedResponse(ctx.uriContext.uri.value.baseUri.replace('/api', '') +
                ctx.uriContext.uri.value.objectUri.substr(0, ctx.uriContext.uri.value.objectUri.length - 1));
        }
        if ('explorer' !== lang) {
            const newLang = locales_helper_1.LocalesHelper.getValidLocales(lang);
            if (newLang !== lang) {
                return new generated_response_2.RedirectGeneratedResponse(ctx.uriContext.uri.value.baseUri +
                    ctx.uriContext.uri.value.objectUri.replace('/' + lang, '/' + newLang));
            }
            ctx.accessRightsContext.user.value = null;
            ctx.accessRightsContext.authorization.value = undefined;
        }
        return undefined;
    }
    async getWebSiteEntity(lang, subPath, pageName, ctx, getCacheName = this.getCachePageName.bind(this)) {
        ctx.uriContext.uri.value.acceptLanguage = lang;
        const webSiteTree = await ctx.webSiteContext.webSiteTree.getOrSetValue(async () => {
            const host = ctx.uriContext.uri.value.host;
            subPath = subPath ? subPath : '';
            let langTree;
            const uri = await this.lookWebSiteEntry(subPath, ctx);
            try {
                langTree = await this.objectTreeService.getNamespaceTree(home_page_const_1.WEB_SITE_VIEW_URL_TYPE.name, host + '$' + subPath, home_page_const_1.WEB_SITE_CACHE_LANG_TYPE.name, lang, services_1.CurrentContext.get(ctx, {}));
            }
            catch (error) {
                await this.objectNodeService.add({
                    parentNodeId: uri.id,
                    name: lang,
                    objectTypeId: home_page_const_1.WEB_SITE_CACHE_LANG_TYPE.name,
                }, services_1.CurrentContext.get(ctx, {
                    nodeContext: { parent: new application_service_1.ExpectedValue(uri) },
                }));
                langTree = await this.objectTreeService.getNamespaceTree(home_page_const_1.WEB_SITE_VIEW_URL_TYPE.name, host + '$' + subPath, home_page_const_1.WEB_SITE_CACHE_LANG_TYPE.name, lang, services_1.CurrentContext.get(ctx, {}));
            }
            ctx.webSiteContext.pageBaseUri.value =
                subPath === ''
                    ? '/' + lang + '/'
                    : '/site/' + subPath + '/' + lang + '/';
            ctx.webSiteContext.siteBaseUriTree.value = langTree;
            for (const cache of ctx.webSiteContext.siteBaseUriTree.value.children) {
                if (getCacheName(pageName) === cache.treeNode.name) {
                    await this.contentEntityService.addTransientContent(models_1.EntityName.objectNode, home_page_const_1.PAGE_CACHE_TYPE.contentType, cache.treeNode);
                    ctx.webSiteContext.cachedContent.value =
                        cache.treeNode.contentPageCache;
                    return undefined;
                }
            }
            let entity = await this.objectTreeService.loadTree(uri.parentNodeId, ctx);
            if (!entity) {
                // TODO: look for entity web site
                entity = await this.objectTreeService.getNamespaceTree(object_tree_const_1.TENANT_TYPE.name, 'Demonstration', travel_story_type_const_1.TRAVEL_STORY_TYPE.name, 'WelcomeSite', ctx);
            }
            return entity;
        });
        return webSiteTree;
    }
    setMeta(adminDOM, name, content) {
        if (adminDOM.window.document.head.querySelector('[name~="' + name + '"][content]')) {
            const meta = adminDOM.window.document.head.querySelector('[name~="' + name + '"][content]');
            meta.name = name;
            meta.content = content;
        }
        else {
            const meta = adminDOM.window.document.createElement('meta');
            meta.name = name;
            meta.content = content;
            adminDOM.window.document.head.append(meta);
        }
    }
    addLinkElement(adminDOM, rel, type, href) {
        const link = adminDOM.window.document.createElement('link');
        link.rel = rel;
        link.type = type;
        link.href = href;
        adminDOM.window.document.head.append(link);
    }
    async renderAdminPage(subPath, ctx) {
        const adminDOM = await jsdom_1.JSDOM.fromFile(path_1.default.join(__dirname, '../../www/index.html'), {});
        // <meta name="objectTrees:rootState_" content="app:view" />
        this.setMeta(adminDOM, 'objectTrees:rootState', 'app:admin');
        //     <meta name="objectTrees:api_" content="http://to.ochoeurdunet.org/api" />
        this.setMeta(adminDOM, 'objectTrees:api', ctx.uriContext.uri.value.baseUri + '/api');
        const siteEntry = await this.lookWebSiteEntry(subPath, ctx);
        const siteOwner = await this.objectNodeService.searchById(siteEntry.parentOwnerId);
        const siteNamespace = siteEntry.parentNamespaceId === siteEntry.parentOwnerId
            ? siteOwner
            : await this.objectNodeService.searchById(siteEntry.parentNamespaceId);
        // <meta name="objectTrees:ownerName" content="Demonstration" />
        this.setMeta(adminDOM, 'objectTrees:ownerName', siteOwner.name);
        // <meta       name="objectTrees:siteId"       content="namespace/Tenant/Demonstration/TravelStory/TravelStoryExample"
        if (siteEntry.parentNamespaceId === siteEntry.parentOwnerId) {
            this.setMeta(adminDOM, 'objectTrees:siteId', `owner/${siteOwner.objectTypeId}/${siteOwner.name}`);
        }
        else {
            this.setMeta(adminDOM, 'objectTrees:siteId', `namespace/${siteOwner.objectTypeId}/${siteOwner.name}/${siteNamespace.objectTypeId}/${siteNamespace.name}`);
        }
        this.addLinkElement(adminDOM, 'icon', 'image/png', (subPath ? '/site/' + subPath : '') + '/favicon.png');
        return new generated_response_2.HtmlGeneratedResponse(ctx, adminDOM.serialize());
    }
    async getWebSitePageNode(entity, pageName, ctx) {
        const webSitePageNode = await ctx.webSiteContext.webSitePageNode.getOrSetValue(async () => {
            let result = undefined;
            const treeNodes = await this.objectNodeService.searchByParentTreeId(entity.id, {
                name: pageName,
                objectTypeIds: await this.objectTypeService.getImplementingTypes(web_site_const_1.PAGE_TYPE.name),
            });
            if (treeNodes && 1 === treeNodes.length) {
                result = treeNodes[0];
            }
            return result;
        });
        return webSitePageNode;
    }
    getPageHref(page, site, ctx) {
        var _a;
        if (page.parentPage) {
            return (ctx.webSiteContext.pageBaseUri.value +
                page.parentPage.pageName +
                '#' +
                page.parentPage.anchor);
        }
        return ctx.webSiteContext.pageBaseUri.value + ((_a = page.treeNode) === null || _a === void 0 ? void 0 : _a.name);
    }
    getPopupHref(page, site, ctx) {
        var _a;
        return (ctx.webSiteContext.pageBaseUri.value + ((_a = page.treeNode) === null || _a === void 0 ? void 0 : _a.name) + '/popup');
    }
    getAdminHref(page, site, ctx) {
        return ('/admin/#/admin/owner/' +
            page.ownerType +
            '/' +
            page.ownerName +
            '/namespace/' +
            page.namespaceType +
            '/' +
            page.namespaceName);
    }
    getCachePageName(pageName = '') {
        return 'cache$' + pageName;
    }
    getCachePopupName(pageName = '') {
        return 'cache$' + pageName + '$popup';
    }
    async getFavicon(ctx, siteName) {
        return new generated_response_1.FileGeneratedResponse(path_1.default.join(__dirname, '/img/favicon.png'), 'favicon.png');
    }
    async redirectToSiteMap(ctx) {
        // TODO : determine site language
        return new generated_response_2.RedirectGeneratedResponse('./fr-FR/sitemap.xml');
    }
    async getLoadingPageResponse(ctx, lang, siteName) {
        if (!lang) {
            return new generated_response_2.RedirectGeneratedResponse(ctx.uriContext.uri.value.baseUri +
                ctx.uriContext.uri.value.objectUri +
                ctx.uriContext.uri.value.acceptLanguage);
        }
        const redirectResponse = this.initLangAndUser(lang, ctx);
        if (redirectResponse) {
            return redirectResponse;
        }
        const entity = await this.getWebSiteEntity(lang, siteName, '', ctx);
        if (ctx.webSiteContext.cachedContent.value) {
            return new generated_response_2.HtmlGeneratedResponse(ctx, ctx.webSiteContext.cachedContent.value.body);
        }
        const result = (await this.actionWebSiteService.getWebSiteAjaxResponse(entity, this.getPageHref.bind(this), this.getAdminHref.bind(this), this.getPopupHref.bind(this), ctx));
        result.json.headerScripts.pageScript = `
function getPageHref(page) {
  let baseUri = '${ctx.webSiteContext.pageBaseUri.value}';
  if (page && page.parentPage) {
    return baseUri + '/' +
      page.parentPage.pageName +
      '#' +
      page.parentPage.anchor;
  }
  return baseUri +
    (page ? '/' + page.treeNode.name : '');
}
`;
        ctx.webSiteContext.cachedContent.value = {
            body: this.actionWebSiteService.getHtmlDocFromAjaxResult(ctx, result),
        };
        await this.storeCachePage('', ctx);
        return new generated_response_2.HtmlGeneratedResponse(ctx, ctx.webSiteContext.cachedContent.value.body);
    }
    async storeCachePage(pageName, ctx, getCacheName = this.getCachePageName.bind(this)) {
        try {
            await this.objectNodeService.add({
                parentNodeId: ctx.webSiteContext.siteBaseUriTree.value.id,
                name: getCacheName(pageName),
                objectTypeId: home_page_const_1.PAGE_CACHE_TYPE.name,
                pageUrl: ctx.uriContext.uri.value.url,
                title: ctx.uriContext.uri.value.url,
                contentPageCache: ctx.webSiteContext.cachedContent.value,
            }, services_1.CurrentContext.get(ctx, {
                nodeContext: {
                    parent: new application_service_1.ExpectedValue(ctx.webSiteContext.siteBaseUriTree.value.treeNode),
                },
            }));
            // eslint-disable-next-line no-empty
        }
        catch (error) { }
    }
    async getWebSitePageResponse(lang, pageName, ctx, siteName) {
        const redirectResponse = this.initLangAndUser(lang, ctx);
        if (redirectResponse) {
            return redirectResponse;
        }
        const webSiteTree = await this.getWebSiteEntity(lang, siteName, pageName, ctx);
        if (ctx.webSiteContext.cachedContent.value) {
            switch (ctx.webSiteContext.cachedContent.value.responseType) {
                case 'xml':
                    return new generated_response_1.XmlGeneratedResponse(ctx, ctx.webSiteContext.cachedContent.value.body);
                default:
                    return new generated_response_2.HtmlGeneratedResponse(ctx, ctx.webSiteContext.cachedContent.value.body);
            }
        }
        // page not yet in cache
        if ('sitemap.xml' === pageName) {
            ctx.webSiteContext.cachedContent.value = {
                body: await this.generateSiteMap(ctx.uriContext.uri.value.protocol +
                    '://' +
                    ctx.uriContext.uri.value.host +
                    ctx.webSiteContext.pageBaseUri.value.substring(0, ctx.webSiteContext.pageBaseUri.value.length - 1), webSiteTree.id),
                responseType: 'xml',
            };
            await this.storeCachePage(pageName, ctx);
            return new generated_response_1.XmlGeneratedResponse(ctx, ctx.webSiteContext.cachedContent.value.body);
        }
        const pageNode = await this.getWebSitePageNode(webSiteTree, pageName, ctx);
        if (pageNode) {
            const result = (await this.actionWebSiteService.getWebSitePageAjaxResponse(webSiteTree, pageNode.id, this.getPageHref.bind(this), this.getAdminHref.bind(this), this.getPopupHref.bind(this), ctx));
            result.json.headerScripts.pageScript = `
    function getPageHref(page) {
      let baseUri = '${ctx.webSiteContext.pageBaseUri.value}';
      if (page && page.parentPage) {
        return baseUri + '/' +
          page.parentPage.pageName +
          '#' +
          page.parentPage.anchor;
      }
      return baseUri +
        (page ? '/' + page.treeNode.name : '');
    }
    `;
            ctx.webSiteContext.cachedContent.value = {
                body: this.actionWebSiteService.getHtmlDocFromAjaxResult(ctx, result),
            };
            await this.storeCachePage(pageName, ctx);
            return new generated_response_2.HtmlGeneratedResponse(ctx, ctx.webSiteContext.cachedContent.value.body);
        }
        else {
            return this.getLoadingPageResponse(ctx);
        }
    }
    async getWebSitePopupResponse(lang, pageName, ctx, siteName) {
        const redirectResponse = this.initLangAndUser(lang, ctx);
        if (redirectResponse) {
            return redirectResponse;
        }
        const webSiteTree = await this.getWebSiteEntity(lang, siteName, pageName, ctx, this.getCachePopupName.bind(this));
        if (ctx.webSiteContext.cachedContent.value) {
            return new generated_response_1.JsonGeneratedResponse(JSON.parse(ctx.webSiteContext.cachedContent.value.body));
        }
        const pageNode = await this.getWebSitePageNode(webSiteTree, pageName, ctx);
        if (pageNode) {
            const popup = (await this.actionWebSiteService.popupWebSiteViewTree(webSiteTree, [pageNode.id], ctx)).json;
            ctx.webSiteContext.cachedContent.value = {
                body: JSON.stringify(popup),
            };
            await this.storeCachePage(pageName, ctx, this.getCachePopupName.bind(this));
            return new generated_response_1.JsonGeneratedResponse(popup);
        }
        else {
            throw application_error_1.ApplicationError.notFound({ popupName: pageName });
        }
    }
    async previewWebSite(entity, args, ctx) {
        return new generated_response_1.XmlGeneratedResponse(ctx, await this.generateSiteMap('', entity.id));
    }
    async getSiteMap(entity, args, ctx) {
        const objectNode = await this.objectNodeService.getNode(entity.treeNode.parentNodeId, services_1.CurrentContext.get(ctx));
        let webSiteUrl = `http://${objectNode.host}`;
        if (objectNode.path) {
            webSiteUrl += `/site/${objectNode.path}`;
        }
        webSiteUrl += '/' + entity.treeNode.name;
        return new generated_response_1.XmlGeneratedResponse(ctx, await this.generateSiteMap(webSiteUrl, entity.parentTreeId));
    }
    async getRobotTxt(entryPath, ctx) {
        return new generated_response_1.TextGeneratedResponse(ctx, `User-agent: *
    Allow: /

    Sitemap: ${ctx.uriContext.uri.value.protocol}://${ctx.uriContext.uri.value.host}${entryPath}sitemap.xml`);
    }
    async generateSiteMap(webSiteUrl, webSiteId) {
        const urls = await this.getSiteUrls(webSiteId, false);
        const date = new Date().toISOString().split('T')[0];
        return `<?xml version="1.0" encoding="UTF-8"?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    ${urls
            .map((url) => `
  <url>
    <loc>${webSiteUrl}${url}</loc>
    <lastmod>${date}</lastmod>
  </url>
    `)
            .join('')}

    </urlset>
    `;
    }
};
HomePageService = tslib_1.__decorate([
    tslib_1.__param(0, core_1.service(action_web_site_service_1.ActionWebSiteService)),
    tslib_1.__param(1, core_1.service(object_tree_service_1.ObjectTreeService)),
    tslib_1.__param(2, core_1.service(object_node_service_1.ObjectNodeService)),
    tslib_1.__param(3, core_1.service(object_type_service_1.ObjectTypeService)),
    tslib_1.__param(4, core_1.service(node_intercept_service_1.NodeInterceptService)),
    tslib_1.__param(5, core_1.service(content_entity_service_1.ContentEntityService)),
    tslib_1.__param(6, core_1.service(application_service_1.ApplicationService)),
    tslib_1.__param(7, core_1.service(action_entity_service_1.ActionEntityService)),
    tslib_1.__param(8, core_1.service(transient_entity_service_1.TransientEntityService)),
    tslib_1.__param(9, core_1.service(inside_rest_service_1.InsideRestService)),
    tslib_1.__metadata("design:paramtypes", [action_web_site_service_1.ActionWebSiteService,
        object_tree_service_1.ObjectTreeService,
        object_node_service_1.ObjectNodeService,
        object_type_service_1.ObjectTypeService,
        node_intercept_service_1.NodeInterceptService,
        content_entity_service_1.ContentEntityService,
        application_service_1.ApplicationService,
        action_entity_service_1.ActionEntityService,
        transient_entity_service_1.TransientEntityService,
        inside_rest_service_1.InsideRestService])
], HomePageService);
exports.HomePageService = HomePageService;
//# sourceMappingURL=home-page.service.js.map