const {title} = require('process');

function newFunction() {
  return {
    ctrl: undefined,
    async init(ctrl) {
      this.ctrl = ctrl;
      // eslint-disable-next-line no-void
      void this.backGroundInit();
    },
    async backGroundInit() {},
    getPageTreeTemplate(pageNode, templateNode, siteTemplateNode) {
      if (pageNode && pageNode.pageTemplateTree) {
        return pageNode.pageTemplateTree;
      }
      if (templateNode && templateNode.pageTemplateTree) {
        return templateNode.pageTemplateTree;
      }
      return siteTemplateNode.pageTemplateTree;
    },
    async initMustache() {
      this.ctrl.navAjax = await this.ctrl.loadAjax(
        this.ctrl.dataTree,
        this.ctrl.templateNode.menuTree,
      );
      this.ctrl.pageAjax = await this.ctrl.loadAjax(
        this.ctrl.pageTree,
        this.getPageTreeTemplate(
          this.ctrl.pageNode,
          this.ctrl.templateNode,
          this.ctrl.siteTemplateNode,
        ),
      );
      if (this.ctrl.dataTree.layout) {
        this.ctrl.layoutAjax = await this.ctrl.loadAjax(
          this.ctrl.dataTree.layout,
          this.ctrl.templateNode.layoutTree,
        );
        this.ctrl.layout = this.ctrl.dataTree.layout.treeNode;
      }
    },
    async getHeaderTags() {
      const tags = {
        equiv:
          '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">',
        revisit: '<meta name="revisit-after" content="30 days">',
        follow: '<meta name="robots" content="index, follow"> ',
      };
      if (this.ctrl.siteNode.metadata) {
        tags.site_metadata = this.ctrl.siteNode.metadata.join(`
  `);
        /**
         *
         *<meta name="language" content="French">
         */
      }
      const keyToField = {
        title: {site: 'webSiteTitle', page: 'pageTitle'},
        description: {site: 'webSiteDescription', page: 'pageDescription'},
        keywords: {site: 'webSiteKeywords', page: 'pageKeywords'},
        author: {site: 'webSiteAuthor', page: 'pageAuthor'},
      };
      for (const key of Object.keys(keyToField)) {
        const info = this.ctrl.pageNode[keyToField[key].page]
          ? this.ctrl.pageNode[keyToField[key].page]
          : this.ctrl.siteNode[keyToField[key].site];

        if (info) {
          if ('title' === key) {
            tags.titleTag = `<title>${info}</title>`;
          }
          tags[key] = `<meta name="${key}" content="${info.replace(
            /"/g,
            '&quot;',
          )}">`;
        }
      }

      return tags;
    },
  };
}
newFunction();
