<template>
<Layout>
  <!-- introductions -->
  <div class="no-folio v-center grow">
    <div v-for="edge in $page.introductions.edges.slice().reverse()" :key="`introductions${edge.node.id}`">
      <VueMarkdown class="intro">{{edge.node.contenu}}
      </VueMarkdown>
    </div>
  </div>

  <div class="blank-page no-folio fill-motif-cross-left" />
  <!-- Auteurs, titre, sous-titre -->
  <div class="column no-folio">
    <div class="fill-motif-cross-right layer-1">

    </div>
    <div class="column layer-2">
      <div class="bold center" v-for="auteur in $static.metadata.authors">
        {{auteur}}
      </div>
      <div class="v-center grow">
        <div class="center">
          <h1 class="main-title center highlight-white" v-html="$static.metadata.title" />

          </br>
          <h2 class="main-pre-title center highlight-white" v-html="$static.metadata.subtitle" />
        </div>
      </div>
      <div class="center">
        <img src="/logo_popsu.png" alt="" style="width:2cm;">
      </div>
    </div>
  </div>
  <!-- Page de fond -->
  <div class="column image-cover image-bleed" v-bind:style='{ backgroundImage: `url(https://popsu-rouen-en.strapi.figli.io/uploads/50424a6a43e44551a4faa699f8ef3caa.JPEG)`, }' />
  <!-- Sommaire -->
  <div class="no-folio column">
    <div class="section-title still">
      Sommaire
    </div>
    <div class="column justify-end table-of-content">
      <span v-for="edge in $page.chapitres.edges.slice().reverse()" :key="`sommaire${edge.node.id}`">
        <a v-if="edge.node.alternatif" v-html="edge.node.alternatif" :href="'#chapitres'+edge.node.id">
        </a>
        <a v-else :href="'#chapitres'+edge.node.id">
          {{ edge.node.Titre }}
        </a>
      </span>
    </div>
  </div>
  <!-- Chapitres -->
  <div v-for="(edge,index) in $page.chapitres.edges.slice().reverse()" :key="`chapitre${edge.node.id}`">
    <div class="blank-page no-folio breakBeforeLeft" />
    <div v-if="edge.node.Rubrique">
      <div class="section-title">
        {{edge.node.Rubrique}}
      </div>
      <VueMarkdown :id="`chapitres${edge.node.id}`" class="chapter-title ">{{edge.node.Titre}}</VueMarkdown>
    </div>
    <div v-else>
      <VueMarkdown :id="`chapitres${edge.node.id}`" class="chapter-title">{{edge.node.Titre}}</VueMarkdown>
    </div>
    <VueMarkdown lang="en-us" class="hyphen chapter-content justify">{{edge.node.Contenu}}
    </VueMarkdown>
  </div>
  <!-- Page blanche -->
  <div class="blank-page no-folio" />
  <!-- Sections -->
  <div v-for="edge in orderBy($page.sections.edges,'node.Ordre')">
    <div v-if="edge.node.espace" class="blank-page no-folio breakBeforeLeft" />
    <h2 :id="`chapitres${edge.node.id}`" class="section-title canbreak still">{{edge.node.Titre}}</h2>
    <VueMarkdown class="section-content">{{edge.node.Contenu}}
    </VueMarkdown>
  </div>
  <!-- Credits -->
  <div class="credits canbreak">
    <div class="credit" v-for="(edge,index) in $page.credits.edges.slice().reverse()" :key="`credits-${edge.node.id}`">
      <h4 v-html="edge.node.Role" />
      <VueMarkdown class="section-content">{{ edge.node.Nom }}</VueMarkdown>
    </div>
  </div>
  <div class="blank-page no-folio fill-green" />
</Layout>
</template>
<script>
const axios = require('axios'),
  path = require('path'),
  param = require(`../../param.JSON`);

import {
  Previewer
} from 'pagedjs'
import VueMarkdown from 'vue-markdown'
import Vue2Filters from 'vue2-filters'

export default {
  mixins: [Vue2Filters.mixin],
  components: {
    VueMarkdown
  },
  mounted() {

    // Ajouter les citations
    let citations = Array.from(document.querySelectorAll("blockquote"));
    citations.forEach((c, index) => {
      c.id = `citation-${index}`;
    });
    // Ajouter les images
    let docImages = Array.from(
      document.querySelectorAll("img")
    )
    let toLoad = docImages.filter(img => img.alt === "insert");

    let imgSource;
    axios.get(path.join(param.source, "images")).then(r => {
      imgSource = r.data;
      let allPromises = [];
      toLoad.forEach(img => {
        let img_id = img.src.split("/").pop();
        let found = imgSource.find(element => element.id == img_id);
        img.src = path.join(param.source, found.images.url);
        img.id = `image-${img_id}`;
        img.parentNode.classList.add("breakBefore");
        let promise = new Promise((resolve, reject) => {
          img.onload = function() {
            let legend = document.createElement("p");
            legend.classList.add("breakAfter");
            legend.classList.add("legend");
            legend.innerHTML = found.legende;
            legend.id = `legend-${img_id}`;
            if (found.double) {
              let clone = img.parentNode.cloneNode(true);
              clone.classList.add("breakBefore");
              clone.querySelector("img").id += "-end";
              img.parentNode.insertBefore(clone, img.previousSibling);
              clone.parentNode.insertBefore(legend, clone.nextSibling);

            } else {
              img.parentNode.insertBefore(legend, img.nextSibling);
            }
            resolve();
          }
        });
        allPromises.push(promise);
      });

      this.$nextTick(function() {
        Promise.all(allPromises).then(() => {
          let previewer = new Previewer();
          previewer.preview().then((flow) => {
            let layouts = Array.from(document.querySelectorAll(".layout"));
            layouts.forEach(l => {
              l.classList.add("full-layout");
            });
            // Centrer les citations
            let citations = Array.from(document.querySelectorAll("blockquote"));
            citations.forEach((citation, i) => {
              let l = citation.closest(".layout");
              l.classList.add("pagequote");
            });
            // Suppression des pages vides
            let pages = Array.from(document.querySelectorAll(".pagedjs_blank_page"));
            pages.forEach((page, i) => {
              let nextPage = document.querySelector(`.pagedjs_page[data-page-number='${parseInt(page.dataset.pageNumber) + 1}']`);
              if (nextPage.querySelector(".blank-page") !== null &&
                nextPage.classList.contains("pagedjs_left_page")
              ) {
                nextPage.parentNode.removeChild(nextPage);
              }
              page.parentNode.removeChild(page);
            });

            let empty = layouts.filter(l=>{
              if(l.firstChild){
                if(l.firstChild.innerHTML.length == 0 && l.firstChild.classList.length == 0) return true;
              }
              if(l.innerHTML.length != 0) return false;
              return true;
            });

            empty.forEach((item, i) => {
              let page = item.closest(".pagedjs_page");
              page.parentNode.removeChild(page);
            });


            // Chercher le dernier paragraphe
            let p = Array.from(document.querySelectorAll(".chapter-content"));
            p[p.length-1].classList.add("last-chapter-p");
          });
        });
      });
    });
  }
};
</script>

<page-query>
  query {
    sections: allSections {
      edges {
        node {
          id
          Titre
          Contenu
          Ordre
          espace
        }
      }
    }

    chapitres: allChapitres {
      edges {
        node {
          id
          Titre
          Contenu
          alternatif
          Rubrique
        }
      }
    }

    introductions: allIntroductions {
      edges {
        node {
          id
          contenu
        }
      }
    }

    credits: allCredits {
      edges {
        node {
          id
          Role
          Nom
        }
      }
    }

  }
</page-query>
<static-query>
query {
  metadata {
    title
    subtitle
    authors
  }
}
</static-query>
