"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ActionWebSiteService = void 0;
const tslib_1 = require("tslib");
const objects_website_1 = require("@jacquesparis/objects-website");
const core_1 = require("@loopback/core");
const helper_1 = require("../../helper");
const generated_response_1 = require("../../helper/generated-response");
const services_1 = require("../../services");
const action_entity_service_1 = require("../../services/action-entity/action-entity.service");
const object_node_service_1 = require("../../services/object-node/object-node.service");
const server_config_service_1 = require("../server-config/server-config.service");
const generated_response_2 = require("./../../helper/generated-response");
const entity_name_1 = require("./../../models/entity-name");
const application_service_1 = require("./../../services/application.service");
const mustache_service_1 = require("./../../services/entity-definition/mustache.service");
const inside_rest_service_1 = require("./../../services/inside-rest/inside-rest.service");
const uri_complete_service_1 = require("./../../services/uri-complete/uri-complete.service");
const web_site_const_1 = require("./web-site.const");
const web_site_service_1 = require("./web-site.service");
let ActionWebSiteService = class ActionWebSiteService {
    constructor(actionEntityService, objectNodeService, uriCompleteService, insideRestService, mustacheService, webSiteService, serverConfigService, objectTypeService) {
        this.actionEntityService = actionEntityService;
        this.objectNodeService = objectNodeService;
        this.uriCompleteService = uriCompleteService;
        this.insideRestService = insideRestService;
        this.mustacheService = mustacheService;
        this.webSiteService = webSiteService;
        this.serverConfigService = serverConfigService;
        this.objectTypeService = objectTypeService;
        this.websiteGenerationService = objects_website_1.WebsiteGenerationService.get();
        this.actionEntityService.registerNewViewFunction(web_site_const_1.WEB_SITE_PROVIDER, ActionWebSiteService.name, 'Build ajax view', entity_name_1.EntityName.objectTree, 'ajax', web_site_const_1.WEB_SITE_VIEW_TYPE.name, this.ajaxWebSiteViewTree.bind(this), 'read');
        this.actionEntityService.registerNewViewFunction(web_site_const_1.WEB_SITE_PROVIDER, ActionWebSiteService.name, 'Build html view', entity_name_1.EntityName.objectTree, 'html', web_site_const_1.WEB_SITE_VIEW_TYPE.name, this.htmlWebSiteViewTree.bind(this), 'read');
        this.actionEntityService.registerNewViewFunction(web_site_const_1.WEB_SITE_PROVIDER, ActionWebSiteService.name, 'Build popup view', entity_name_1.EntityName.objectTree, 'popup', web_site_const_1.WEB_SITE_VIEW_TYPE.name, this.popupWebSiteViewTree.bind(this), 'read');
        this.actionEntityService.registerNewMethodFunction(web_site_const_1.WEB_SITE_PROVIDER, ActionWebSiteService.name, 'Add text in an existing paragraph', entity_name_1.EntityName.objectNode, 'addText', web_site_const_1.PAGE_WITH_SUB_PAGE_TYPE.name, this.addText.bind(this), 'update');
        this.actionEntityService.registerNewMethodFunction(web_site_const_1.WEB_SITE_PROVIDER, ActionWebSiteService.name, 'Add paragraph in an existing paragraph', entity_name_1.EntityName.objectNode, 'addParagraph', web_site_const_1.PAGE_WITH_SUB_PAGE_TYPE.name, this.addParagraph.bind(this), 'update');
        this.actionEntityService.registerNewMethodFunction(web_site_const_1.WEB_SITE_PROVIDER, ActionWebSiteService.name, 'Add event entry', entity_name_1.EntityName.objectNode, 'addEvent', web_site_const_1.PAGE_WITH_SUB_PAGE_TYPE.name, this.addEvent.bind(this), 'update');
        this.doc = helper_1.contentGenericTemplate(__dirname, 'doc');
    }
    async popupWebSiteViewTree(entity, args, ctx) {
        const objectNode = await this.objectNodeService.getNode(args[0], application_service_1.CurrentContext.get(ctx, {}));
        return new generated_response_2.JsonGeneratedResponse(await this.webSiteService.getPopupContent(entity.treeNode.popupLinkLabels, objectNode, ctx));
    }
    async htmlWebSiteViewTree(entity, args, ctx) {
        const result = await this.ajaxWebSiteViewTree(entity, args, ctx);
        result.json.headerScripts.pageScript = `
    function getPageHref(page) {
      let baseUri = '${this.uriCompleteService.getUri(entity_name_1.EntityName.objectTree, entity.id, ctx)}/view/html';
      if (page && page.parentPage) {
        return baseUri + '/' +
          page.parentPage.pageId +
          '#' +
          page.parentPage.anchor;
      }
      return baseUri +
        (page ? '/' + page.treeNode.id : '');
    }
    `;
        return this.getHtmlDocResponseFromAjaxResult(ctx, result);
    }
    getHtmlDocResponseFromAjaxResult(ctx, response) {
        return new generated_response_2.HtmlGeneratedResponse(ctx, this.getHtmlDocFromAjaxResult(ctx, response));
    }
    getHtmlDocFromAjaxResult(ctx, response) {
        var _a, _b, _c, _d;
        let result = undefined;
        if (response instanceof generated_response_1.TextGeneratedResponse) {
            const options = {
                body: response.response,
                headerScript: this.doc.headerScript,
                headerTags: {},
            };
            if ((_b = (_a = ctx.webSiteContext) === null || _a === void 0 ? void 0 : _a.pageBaseUri) === null || _b === void 0 ? void 0 : _b.value) {
                options.headerTags.refIcon = `<link rel="icon" type="image/png" href="${ctx.webSiteContext.pageBaseUri.value.replace('/' + ctx.uriContext.uri.value.acceptLanguage + '/', '/favicon')}.png">`;
            }
            result = this.mustacheService.parse(this.doc.templateMustache, options);
        }
        else if (response instanceof generated_response_2.JsonGeneratedResponse) {
            const docParts = response.json;
            docParts.headerScript = this.doc.headerScript;
            if (!docParts.headerTags.refIcon && ((_d = (_c = ctx.webSiteContext) === null || _c === void 0 ? void 0 : _c.pageBaseUri) === null || _d === void 0 ? void 0 : _d.value)) {
                docParts.headerTags.refIcon = `<link rel="icon" type="image/png" href="${ctx.webSiteContext.pageBaseUri.value.replace('/' + ctx.uriContext.uri.value.acceptLanguage + '/', '/favicon')}.png">`;
                docParts.lang = ctx.uriContext.uri.value.acceptLanguage.substring(0, 2);
            }
            result = this.mustacheService.parse(this.doc.templateMustache, docParts);
        }
        return result;
    }
    getPageHref(page, site, ctx) {
        const viewId = site.id +
            '/view/html' +
            (page
                ? '/' +
                    (page.parentPage
                        ? page.parentPage.pageId
                        : page.treeNode.id)
                : '') +
            (page && page.parentPage ? '#' + page.parentPage.anchor : '');
        return this.uriCompleteService.getUri(entity_name_1.EntityName.objectTree, viewId, ctx);
    }
    getPopupHref(page, site, ctx) {
        const viewId = site.id +
            '/view/popup' +
            (page ? '/' + page.treeNode.id : '');
        return this.uriCompleteService.getUri(entity_name_1.EntityName.objectTree, viewId, ctx);
    }
    getAdminHref(page, site, ctx) {
        return ('/admin/#/admin/owner/' +
            page.ownerType +
            '/' +
            page.ownerName +
            '/namespace/' +
            page.namespaceType +
            '/' +
            page.namespaceName);
    }
    async getWebSiteAjaxResponse(webSiteTree, getPageHref, getAdminHref, getPopupHref, ctx) {
        return this.ajaxWebSiteViewTree(webSiteTree, {}, ctx, getPageHref, getAdminHref, getPopupHref);
    }
    async getWebSitePageAjaxResponse(webSiteTree, pageNodeId, getPageHref, getAdminHref, getPopupHref, ctx) {
        return this.ajaxWebSiteViewTree(webSiteTree, { 0: pageNodeId }, ctx, getPageHref, getAdminHref, getPopupHref);
    }
    async ajaxWebSiteViewTree(entity, args, ctx, getPageHref = this.getPageHref.bind(this), getAdminHref = this.getAdminHref.bind(this), getPopupHref = this.getPopupHref.bind(this)) {
        ctx.webSiteContext.generationContext.debug = await this.serverConfigService.get('debugGeneration', () => Promise.resolve(false));
        const ajaxResult = await this.websiteGenerationService.getAjaxContent({
            getCachedOrRemoteObjectById: async (treeId) => {
                try {
                    return (await this.insideRestService.read(this.uriCompleteService.getUri(entity_name_1.EntityName.objectTree, treeId, ctx), ctx));
                }
                catch (error) {
                    return { children: [], treeNode: { name: 'unknown' } };
                }
            },
        }, {
            getCachedOrRemoteObjectById: async (nodeId) => {
                try {
                    return (await this.insideRestService.read(this.uriCompleteService.getUri(entity_name_1.EntityName.objectNode, nodeId, ctx), ctx));
                }
                catch (error) {
                    return { name: 'unknown' };
                }
            },
        }, {
            getPageHref: (page) => {
                return getPageHref(page, entity, ctx);
            },
            getAdminHref: (page) => {
                return getAdminHref(page, entity, ctx);
            },
            getPopupHref: (page) => {
                return getPopupHref(page, entity, ctx);
            },
        }, ctx.webSiteContext.generationContext, entity.id, args[0], args[1], args[2]);
        return new generated_response_2.JsonGeneratedResponse(ajaxResult);
    }
    async addText(objectNode, args, ctx) {
        if (!args.text) {
            throw helper_1.ApplicationError.missingParameter('text');
        }
        const objectType = await ctx.nodeContext.objectType.getOrSetValue(async () => {
            return this.objectTypeService.searchById(objectNode.objectTypeId);
        });
        let childObjectType;
        for (const subType of objectType.objectSubTypes) {
            if ((await this.objectTypeService.getImplementedTypes(subType.subObjectTypeId)).includes(web_site_const_1.PAGE_TYPE.name)) {
                childObjectType = subType.subObjectTypeId;
                break;
            }
        }
        if (!childObjectType) {
            throw helper_1.ApplicationError.incompatible({
                parentType: objectNode.objectTypeId,
                childType: web_site_const_1.PAGE_TYPE.name,
            });
        }
        args.text = args.text.replace(/\r\n/, '\n');
        args.text = args.text.replace(/\n\r/, '\n');
        args.text = args.text.replace(/\r/, '\n');
        const texts = args.text.split('\n');
        for (const text of texts) {
            if (text) {
                await this.objectNodeService.add({
                    parentNodeId: objectNode.id,
                    objectTypeId: childObjectType,
                    contentText: text,
                }, application_service_1.CurrentContext.get(ctx, {
                    nodeContext: { parent: new application_service_1.ExpectedValue(objectNode) },
                }), false, true, true);
            }
        }
    }
    async addEvent(objectNode, args, ctx) {
        if (!args.title) {
            throw helper_1.ApplicationError.missingParameter('title');
        }
        const objectType = await ctx.nodeContext.objectType.getOrSetValue(async () => {
            return this.objectTypeService.searchById(objectNode.objectTypeId);
        });
        let childObjectType;
        for (const subType of objectType.objectSubTypes) {
            if ((await this.objectTypeService.getImplementedTypes(subType.subObjectTypeId)).includes(web_site_const_1.PAGE_TYPE.name)) {
                childObjectType = subType.subObjectTypeId;
                break;
            }
        }
        if (!childObjectType) {
            throw helper_1.ApplicationError.incompatible({
                parentType: objectNode.objectTypeId,
                childType: web_site_const_1.PAGE_TYPE.name,
            });
        }
        const eventNode = {
            parentNodeId: objectNode.id,
            objectTypeId: childObjectType,
            title: args.title,
            menuTitle: args.title,
            paragraphTitle: args.title,
        };
        await this.webSiteService.completeEventObjectNodeCreation(eventNode, args);
        return this.objectNodeService.add(eventNode, ctx, false, true, true);
    }
    async addParagraph(objectNode, args, ctx) {
        if (!args.title) {
            return this.addText(objectNode, args, ctx);
        }
        const objectType = await ctx.nodeContext.objectType.getOrSetValue(async () => {
            return this.objectTypeService.searchById(objectNode.objectTypeId);
        });
        let childObjectType;
        for (const subType of objectType.objectSubTypes) {
            if ((await this.objectTypeService.getImplementedTypes(subType.subObjectTypeId)).includes(web_site_const_1.PAGE_TYPE.name)) {
                childObjectType = subType.subObjectTypeId;
                break;
            }
        }
        if (!childObjectType) {
            throw helper_1.ApplicationError.incompatible({
                parentType: objectNode.objectTypeId,
                childType: web_site_const_1.PAGE_TYPE.name,
            });
        }
        const parentNode = await this.objectNodeService.add({
            parentNodeId: objectNode.id,
            objectTypeId: childObjectType,
            title: args.title,
            paragraphTitle: args.title,
        }, ctx, false, true, true);
        return this.addText(parentNode, args, application_service_1.CurrentContext.get(ctx, {
            nodeContext: { node: new application_service_1.ExpectedValue(parentNode) },
        }));
    }
};
ActionWebSiteService = tslib_1.__decorate([
    tslib_1.__param(0, core_1.service(action_entity_service_1.ActionEntityService)),
    tslib_1.__param(1, core_1.service(object_node_service_1.ObjectNodeService)),
    tslib_1.__param(2, core_1.service(uri_complete_service_1.UriCompleteService)),
    tslib_1.__param(3, core_1.service(inside_rest_service_1.InsideRestService)),
    tslib_1.__param(4, core_1.service(mustache_service_1.MustacheService)),
    tslib_1.__param(5, core_1.service(web_site_service_1.WebSiteService)),
    tslib_1.__param(6, core_1.service(server_config_service_1.ServerConfigService)),
    tslib_1.__param(7, core_1.service(services_1.ObjectTypeService)),
    tslib_1.__metadata("design:paramtypes", [action_entity_service_1.ActionEntityService,
        object_node_service_1.ObjectNodeService,
        uri_complete_service_1.UriCompleteService,
        inside_rest_service_1.InsideRestService,
        mustache_service_1.MustacheService,
        web_site_service_1.WebSiteService,
        server_config_service_1.ServerConfigService,
        services_1.ObjectTypeService])
], ActionWebSiteService);
exports.ActionWebSiteService = ActionWebSiteService;
//# sourceMappingURL=action-web-site.service.js.map