import { Template } from '../template.js';
import { Sidemenu } from '../../component/components/sidemenu.js';
import { Breadcrumb } from '../../component/components/breadcrumb.js';
import { TOC } from '../../page/body/toc.js';
import { Edit } from '../../page/body/edit.js';
import { Mesh } from '../../page/body/mesh.js';
import { Badges } from '../../page/body/badges.js';

class EditorialTemplate extends Template {
  constructor (data) {
    super(data, true);

    this._hasSidemenu = data?.resource?.navigation?.sidemenu !== undefined;
    if (this._hasSidemenu) this._sidemenu = new Sidemenu(data.resource.navigation.sidemenu, data.resource.badge);

    this._breadcrumb = new Breadcrumb(data.breadcrumb);

    this._toc = new TOC(data, this.content.nodes);
  }

  structure (data) {
    this._hasEditUrl = data?.editUrl != null;
    this._hasMesh = data?.mesh?.items?.length;
    this._hasBadge = data?.badge != null;

    if (this._hasBadge) {
      const badges = new Badges({ids: data.badge, resource: data.resource.badge});
      data.nodes.unshift(badges.node);
    }

    if (this._hasEditUrl) {
      const edit = new Edit({...data.resource.edit, editUrl: data.editUrl, blankLabel: data.fragments.blank});
      data.nodes.push(edit.node);
    }

    if (this._hasMesh) {
      const mesh = new Mesh({...data.resource.mesh, ...data.mesh});
      data.nodes.push(mesh.node);
    }

    return super.structure(data);
  }

  async render () {
    const cols = [];
    if (this._hasSidemenu) {
      cols.push(`
                <div class="fr-col-12 fr-col-md-4">
                    ${await this._sidemenu.render()}
                </div>
            `);
    }

    cols.push(`
                <div class="content-editorial fr-col-12 fr-col-md-8">
                    ${await this._breadcrumb.render()}
                    ${await this._toc.render()}
                    ${await super.render()}
                </div>
            `);

    return `
            <div class="fr-container">
                <div class="fr-grid-row fr-grid-row--gutters fr-grid-row--center">
                    ${cols.join('')}
                 </div>
            </div>`;
  }
}

EditorialTemplate.NAME = 'editorial';

export { EditorialTemplate };
