<template>
  <div class="main" id='annomain'>
    <v-dialog v-model="showCorrectionDialog" hide-overlay persistent width='600'>
      <v-card>
        <v-card-title class="white pl-6 flex py-2 items-center text-md-left text-white" style=" font-size:20px; color: #00063d; font-weight: bold; line-height: 20px;">
          Ceci est une analyse automatique générée par différentes Intelligences artificielles que Dokoma <br /> a agrégées.
        </v-card-title>
        <v-card-text class="pa-6 secondary" >
        <div  v-html="correctionAi" style="white-space: pre-line;background-color: #00063d; font-size:18px ; color: white;overflow-y: auto;  max-height: 400px;"></div>
        </v-card-text>
        <v-btn style="width:100%; border-radius: 0 0 10px 10px;" color="white" @click='showCorrectionDialog = false'>
          Fermer
        </v-btn>
      </v-card>
    </v-dialog>
    <button v-if="correctionAi"  class="robot-button" type="button" title="Ai" @click='showCorrectionDialog = true'>
      <span class='mdi mdi-robot'></span>
    </button>
    <button :class="{'fullsize' : commentsVisibility}" class="close-button" type="button" title="Fermer" data-tooltype="close" @click='closeEvent'>
      <span class='mdi mdi-close'></span>
    </button>
    <div class="zoom-wrapper"  :class="{'fullsize' : commentsVisibility, 'top-offset' : commentWrapper}">
      <button type="button" title="Réduire" data-tooltype="point" @click='resizeDocument("up")'>
        <span class='mdi mdi-magnify-plus'></span>
      </button>
      <button type="button" title="Agrandir" data-tooltype="point" @click='resizeDocument("down")'>
        <span class='mdi mdi-magnify-minus'></span>
      </button>
    </div>
    <div class="toolbar" :class="{'fullsize' : commentsVisibility, 'bigger-toolbar' : commentWrapper}" v-if="toolbar">
      <button class="cursor top-button" type="button" title="Curseur" data-tooltype="cursor">
        <span class='mdi mdi-cursor-default-outline'></span>
      </button>
      <div class="item-spacer"></div>

      <button class="eraser" type="button" title="Effacer" data-tooltype="eraser">
        <span class='mdi mdi-eraser-variant'></span>
      </button>
      <div class="item-spacer"></div>
      <!-- <button class="rectangle" type="button" title="Rectangle" data-tooltype="area">&nbsp;</button>
      <button class="circle" type="button" title="Circle" data-tooltype="circle">○</button>
      <button class="circle" type="button" title="fillCircle" data-tooltype="fillcircle">◉</button>
      <button class="circle" type="button" title="emptyCircle" data-tooltype="emptycircle">⦿</button>
      <button class="arrow" type="arrow" title="Arrow" data-tooltype="arrow">➤</button>  -->
      <!-- <div class="hotspot-color"></div> -->

      <!-- <button class="highlight" type="button" title="Highlight" data-tooltype="highlight">&nbsp;</button>
      <button class="strikeout" type="button" title="Strikeout" data-tooltype="strikeout">&nbsp;</button> -->

      <!-- <div class="item-spacer"></div> -->
      <div style='position: relative;'>
        <button class="text" type="button" title="Écrire" data-tooltype="math">
          <span class='mdi mdi-function-variant'></span>
        </button>
      </div>
      <div class="item-spacer"></div>

      <div style='position: relative;'>
        <button class="text" type="button" title="Écrire" data-tooltype="text">
          <span class='mdi mdi-format-text'></span>
        </button>
      </div>
      <select class="text-size outer-select"></select>
      <div class="item-spacer"></div>
      <div style='position: relative;'>
        <button class="pen" type="button" title="Dessiner" data-tooltype="draw">
          <span class='mdi mdi-pencil'></span>
        </button>
      </div>
      <select class="pen-size outer-select"></select>

      <div class="item-spacer"></div>
      <div class="hotspot-color admin-color"></div>
      <template v-if='commentWrapper'>
        <div class="item-spacer"></div>
        <button class="comment" type="button" title="Ajouter un commentaire" data-tooltype="point">
          <span class='mdi mdi-comment-plus-outline'></span>
        </button>
      </template>
      <div class="item-spacer"></div>

      <a href="javascript://" class="clear" title="Effacer mes notes">
        <span class='mdi mdi-trash-can-outline'></span>
      </a>
      <div class='spacer'></div>
    </div>
    <div id="content-wrapper" :class="{'fullsize' : !commentsVisibility, 'full-height': !toolbar }">
      <div id="viewer" class="pdfViewer"></div>
    </div>
    <template v-if='commentWrapper'>
      <div id="comment-wrapper" :class="{'active' : commentsVisibility, 'full-height': !toolbar}">
        <button class='drawer-button' @click='toggleDrawer()'>
          <span class='mdi mdi-comment-search-outline'></span>
        </button>
        <div class="comment-list">
          <h4>Commentaires</h4>
          <div class="comment-list-container">
            <div class="comment-list-item">Aucun commentaire</div>
          </div>
          <div class="comment-list-form__wrapper" style="display:none;" :class="{'hidden-content' : !toolbar}">
            <button class='input-type-toggle' disabled='!toolbar' @click='toggleMathKeyboard(); return false;'>
              <span class='mdi mdi-sync'></span>
              {{mathKeyboard ? 'Clavier régulier' : 'Clavier mathématique'}}
            </button>
            <form>
              <fieldset disabled='!toolbar'>
                <div class='comment-list-form'>
                  <math-field v-if='mathKeyboard' virtual-keyboard-mode="manual" ignore-spacebar-in-math-mode='true' use-shared-virtual-keyboard id='mathComm'></math-field>
                  <textarea v-else type="text" placeholder="Ajouter un commentaire" id="normalComm"/>
                </div>
              </fieldset>
            </form>
            <!-- PAS NECESSAIRE DE SORTIR LE BOUTON SI ON GARDAIT RETURN FALSE SUR LE CLICK LES ACTIONS SUR LE FORM ETAIT FAITES POUR PAS AVOIR DE RELOAD -->
            <button class='input-type-answer' disabled='!toolbar' @click='saveComment(); return false;'>Enregistrer le commentaire</button>
          </div>
        </div>
      </div>
    </template>
    <desmos-modal v-if='showDesmos' @toogleDesmos='showDesmos = false' :desmosExpressions='desmosExpressions'></desmos-modal>
  </div>
</template>

<script>
import 'pdfjs-dist/build/pdf.worker.entry';
import PDFJSAnnotate from './PDFJSAnnotate';
const pdfjsLib = require('pdfjs-dist');
import { CUSTOM_KEYBOARD_LAYER } from './UI/keyboardOptions.js';
import initColorPicker from './initColorPicker';
import "./css/toolbar.css";
import "./css/pdf_viewer.css";
import 'mathlive/dist/mathlive-fonts.css';
import 'mathlive/dist/mathlive-static.css';
import desmosModal from './desmosModal.vue';

let pdfjsViewer = null
let MathLive = null
if (typeof window !== 'undefined' && 'Worker' in window) {
  pdfjsViewer = require('pdfjs-dist/web/pdf_viewer.js');
  MathLive = require('mathlive/dist/mathlive.mjs');
}

const { UI } = PDFJSAnnotate;
PDFJSAnnotate.setStoreAdapter(new PDFJSAnnotate.LocalStoreAdapter());

export default {
  components: { desmosModal },
  name: 'pdfAnnotateVue',
  data() {
    return{
      showCorrectionDialog: false,
      showDesmos: false,
      documentId: null,
      annotationId: null,
      viewer: null,
      dataUser: [{"id":"13R","type":"textarea","value":"Les données devraient apparaître rapidement..."}],
      PAGE_HEIGHT: 1,
      NUM_PAGES: 0,
      renderedPages: [],
      okToRender: false,
      RENDER_OPTIONS:{
        documentId: this.src,
        pdfDocument: null,
        textLayerFactory: new pdfjsViewer.DefaultTextLayerFactory(),
        annotationLayerFactory: new pdfjsViewer.DefaultAnnotationLayerFactory(),
        renderInteractiveForms: true,
        scale: parseFloat(localStorage.getItem(`${this.src}/scale`), 10) || 1.0,
        rotate: parseInt(localStorage.getItem(`${this.src}/rotate`), 10) || 0
      },
      observer: null,
      viewComments: true,
      selectedScale: parseFloat(localStorage.getItem(`${this.src}/scale`), 10) || 1.0,
      mathKeyboard: false,
      desmosExpressions: []
    }
  },
  props: {
    src: {
      type: [String],
      default: '',
    },
    toolbar: {
      type: Boolean,
      default: false
    },
    commentWrapper: {
      type: Boolean,
      default: false
    },
    page: {
      type: Number,
      default: 1,
    },
    rotate: {
      type: Number,
      default: 0,
    },
    scale: {
      type: [Number, String],
      default: 1,
    },
    resize: {
      type: Boolean,
      default: false,
    },
    data: {
      type: String,
      default: '',
    },
    commentaires: {
      type: Object,
      default: null
    },
    ia: {
      type: Object,
      default: null
    },
    mathfields: {
      type: Boolean,
      default: false
    },
    origin: {
      type: String,
      default: ''
    },
    isCorrectionAI: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    src: function(val) {
      this.RENDER_OPTIONS.documentId = val
      this.render()
    },
    data (newVal) {
      if (newVal) {
        this.render()
      }
    },
    commentaires (newVal) {
      if (newVal) {
        this.renderComments()
      }
    },
    // page: function (val) {
    //   // var self = this;
    //   // this.pdf.getPage(val).then(function (pdfPage) {
    //   //   self.pdfViewer.setPdfPage(pdfPage);
    //   //   self.pdfViewer.draw();
    //   // });
    // },
    // scale: function (val) {
    //   // this.drawScaled(val);
    // },
    // rotate: function (newRotate) {
    //   // if (this.pdfViewer) {
    //   //   this.pdfViewer.update(this.scale,newRotate);
    //   //   this.pdfViewer.draw();
    //   // }
    // },
  },
  beforeDestroy () {
    // for (let i = 0; i < this.NUM_PAGES; i++) {
    //   window.document.querySelector(`div#pageContainer${i + 1} svg.annotationLayer`).innerHTML = '';
    // }
    UI.disableEraser();
    UI.disablePen(true);
    UI.disableText(true);
    UI.disableRect(true);
    UI.disableCircle(true);
    UI.disableArrow(true);
    UI.disablePoint(true);
    UI.disableMathText(true);
    UI.disableEdit(true);
    localStorage.removeItem(`${this.RENDER_OPTIONS.documentId}/annotations`);
  },
  computed: {
    commentsVisibility () {
      if (this.commentWrapper) {
        return this.viewComments;
      } else {
        return false;
      }
    },
    correctionAi() {
      return this.ia?.description
    }
  },
  mounted () {
    localStorage.removeItem(`${this.RENDER_OPTIONS.documentId}/annotations`);
    window.document.getElementById('content-wrapper').addEventListener('scroll', (e) => {
      let visiblePageNum = Math.round(e.target.scrollTop / self.PAGE_HEIGHT) + 1;
      let visiblePage = window.document.querySelector(`.page[data-page-number="${visiblePageNum}"][data-loaded="false"]`);

      if (self.renderedPages.indexOf(visiblePageNum) === -1) {
        self.okToRender = true;
        self.renderedPages.push(visiblePageNum);
      }
      else {
        self.okToRender = false;
      }

      if (visiblePage && self.okToRender) {
        UI.renderPage(visiblePageNum, self.RENDER_OPTIONS)
      }
    });
    setTimeout(() => {
      this.render().then(() => {
            if(this.toolbar){
              this.HotspotColorStuff()
              this.TextStuff()
              this.PenStuff()
              this.ToolbarButtons()
              this.ClearToolbarButton()
              // MEthod custom à la place
              // this.ScaleAndRotate()
            }
        
            if(this.commentWrapper){
              this.CommentStuff()
            }
  
      })
    });
    const self = this
    window.onbeforeunload = function () {
      localStorage.removeItem(`${self.RENDER_OPTIONS.documentId}/annotations`)
      if (self.observer) {
        self.observer.disconnect()
      }
    }
  },
  methods: {
    toggleMathKeyboard () {
      this.mathKeyboard = !this.mathKeyboard
    },
    closeEvent () {
      if (this.RENDER_OPTIONS.pdfDocument) {
        this.RENDER_OPTIONS.pdfDocument.destroy()
      }
      this.$emit('close')
    },
    renderComments () {
      this.addCommentaires()
      this.subscribeEvent()
    },
    toggleExtraMenu (element) {
      // if (this.activeMenu === element) {
      //   this.activeMenu = null
      // } else {
      this.activeMenu = element
      // if (element === 'draw') {
      //   // initColorPicker(document.querySelector('.pen-color'), penColor, function(value) {
      //   //   setPen(penSize, value);
      //   // })
      //   // this.PenStuff()
      //   // this.HotspotColorStuff()
      // } else if (element === 'text') {
      //   // this.TextStuff()
      // }
      // }
    },
    toggleDrawer () {
      // this.commentWrapper = !this.commentWrapper
      this.viewComments = !this.viewComments
    },
    subscribeEvent () {
      const temp = window.document.querySelectorAll('svg#svgannotate.annotationLayer')
      const tempCorrectionAI = window.document.getElementById('svgannotateAI')
      // ce que l'on veut ecouté
      const conf = {
        subtree: true,
        attributes: true,
        childList: true,
        characterData: true
      }
      const self = this
      const callback = async function (listmut, observer) {
        // on doit checker si on a des commentaire
        const comment = await PDFJSAnnotate.getStoreAdapter().getAllComments(self.RENDER_OPTIONS.documentId, 1).then((data) => {
          return data
        })
        if (tempCorrectionAI?.innerHTML) {
          self.$emit('changeSvg', { svg: temp[0].outerHTML, commentaires: comment, correction: tempCorrectionAI.innerHTML })
        } else {
          self.$emit('changeSvg', { svg: temp[0].outerHTML, commentaires: comment})
        }
        // for(const mutation of listmut) {
        //   if (mutation.type === 'childList') {
        //       console.log('A child node has been added or removed.');
        //   }
        //   else {
        //       console.log('The ' + mutation+ ' attribute was modified.');
        //   }
        // }
      }
      if (temp[0]) {
        if (this.observer) {
          this.observer.disconnect()
        }
        this.observer = new MutationObserver(callback)
        setTimeout(() => {
          self.observer.observe(temp[0], conf)
        }, 500)
      }
      // const comment = window.document.getElementById('pageContainer1')
      // comment.addEventListener('comment:add', (event) => {
      //   console.log('on a un ajout de comm', event)
      // })
      // comment.addEventListener('annotation:edit', (event) => {
      //   console.log('on a modifie un commentaire', event)
      // })
      // comment.addEventListener('comment:delete', (event) => {
      //   console.log('on a supprimé un commentaire', event)
      // })
    },
    launchData () {
      this.$emit('setLoading', true)
      this.addData()
      this.addCommentaires()
      this.setMath()
      this.subscribeEvent()
      this.renderComments()
      this.$emit('setLoading', false)
    },
    async render () {
      const self = this
      self.viewer = window.document.getElementById('viewer');
      const pdf = await pdfjsLib.getDocument(this.RENDER_OPTIONS.documentId).promise
      self.RENDER_OPTIONS.pdfDocument = pdf;

      self.viewer.innerHTML = '';
      self.NUM_PAGES = pdf.numPages;
      let isCorrection = false;
      if (this.commentaires?.ia && JSON.parse(this.commentaires?.ia)?.description) {
        isCorrection = true
      }
      if (!this.isCorrectionAI) {
        isCorrection = false;
      }
      for (let i = 0; i < self.NUM_PAGES; i++) {
        let page = UI.createPage(i + 1, isCorrection);
        self.viewer.appendChild(page);
      }
      
      const [pdfPage] = await UI.renderPage(1, self.RENDER_OPTIONS)
      let viewport = pdfPage.getViewport({ scale: self.RENDER_OPTIONS.scale })
      self.PAGE_HEIGHT = viewport.height
      self.launchData()
    },
    setMath () {
      if (this.mathfields) {
        const temp = window.document.getElementsByClassName('textWidgetAnnotation')
        temp.forEach((element, index) => {
          const test = window.document.createElement('div')
          test.setAttribute('id', 'latex-' + index)
          test.setAttribute('class', 'annotationLayer')
          test.setAttribute('data-annotation-id', element.getAttribute('data-annotation-id'))
          test.innerHTML = element.firstChild.value
          element.appendChild(test)
          element.firstChild.style.opacity = -1 // ON CACHE LE TEXTAREA
          const self = this
          MathLive.makeMathField('latex-' + index, {
            smartMode: true,
            virtualKeyboardMode: 'manual',
            locale: 'fr-CA',
            customVirtualKeyboardLayers: CUSTOM_KEYBOARD_LAYER,
            customVirtualKeyboards: { 'custom-keyboard': { label: '123', tooltip: 'Numérique', layer: 'custom-layer' } },
            virtualKeyboards: 'custom-keyboard symbols'
          })
          // OVERRIDE CUSTOM POUR CHANGER LE TOOLTIP
          if (document.querySelector('[data-ml__tooltip]')) {
            const btn = document.querySelector('[data-ml__tooltip]')
            btn.setAttribute('data-ml__tooltip', 'Insérer une fonction mathématique')
          }
          if (this.data) {
            const temp = JSON.parse(this.data)
            const filterElem = temp.filter((e) => {
              if (e && e.id) {
                return parseInt(e.id.split('-')[1]) === parseInt(index) || parseInt(e.id) === parseInt(index)
              }
            })
            if (filterElem.length > 0) {
              filterElem.forEach((data) => {
                this.addMathLine(index, test, element, data.id, data.value)
              })
            }
          }
        })
      }
    },
    addMathLine (index, wrapperDiv, ref, id, value) {
      const long = wrapperDiv.children.length - 1
      const wrapper = window.document.createElement('div')
      const lastElem = wrapperDiv.lastElementChild
      wrapper.setAttribute('id', id || index + '-' + long)
      wrapper.setAttribute('class', 'math-elem')
      wrapper.setAttribute('data-annotation-id', ref.getAttribute('data-annotation-id'))
      wrapperDiv.appendChild(wrapper)
      if (value) {
        wrapper.innerHTML = value
      }
      // on mets le bouton en dessous
      wrapperDiv.insertBefore(wrapper, lastElem)
      const self = this
      MathLive.makeMathField(id || index + '-' + long, {
        smartMode: true,
        virtualKeyboardMode: 'manual',
        locale: 'fr-CA',
        customVirtualKeyboardLayers: CUSTOM_KEYBOARD_LAYER,
        customVirtualKeyboards: { 'custom-keyboard': { label: '123', tooltip: 'Numérique', layer: 'custom-layer' } },
        virtualKeyboards: 'custom-keyboard symbols'
      })
    },
    addCommentaires () {
      let temp = null
      let correction = null
      if (this.commentaires && this.commentaires.data) {
        temp = JSON.parse(this.commentaires.data).donnees
      }
      if (this.ia?.description) {
        correction = this.ia.description
      }
      const elemtoReplace = window.document.querySelectorAll('svg#svgannotate.annotationLayer')
      const elemtoReplaceAI = window.document.getElementById('svgannotateAI')
      if (correction && elemtoReplaceAI) {
        elemtoReplaceAI.innerHTML = correction
      }
      
      if (elemtoReplace[0]) {
        if (temp) {
          elemtoReplace[0].innerHTML = temp.svg
          const Nodes = Array.prototype.slice.call(elemtoReplace[0].childNodes[0].childNodes)
          Nodes.forEach(function (el) {
            elemtoReplace[0].appendChild(el)
          })
          // ON DOIT SUPPRIMER LES ELEMENTS SVG DUPLIQUES EVENTUELS
          const self = this
          this.$nextTick(() => {
            this.scaleSVG()
            setTimeout(() => {
              self.scaleSVG()
            }, 500)
          })
        }
        if (temp && temp.commentaires) {
          temp.commentaires.forEach((commentaire) => {
            PDFJSAnnotate.getStoreAdapter().addComment(this.RENDER_OPTIONS.documentId, commentaire.annotation, commentaire.html)
          })
        }
      }
      if (temp && temp.commentaires) {
        temp.commentaires.forEach((commentaire) => {
          PDFJSAnnotate.getStoreAdapter().addComment(this.RENDER_OPTIONS.documentId, commentaire.annotation, commentaire.html)
        })
      }
    },
    scaleSVG () {
      const elemtoReplace = window.document.querySelectorAll('svg#svgannotate.annotationLayer')
      if (elemtoReplace.length > 0) {
        for (let i = 0; i < elemtoReplace[0].children.length; i++) {
          const el = elemtoReplace[0].children[i]
          if (el.classList && el.classList.contains('annotationLayer')) {
            elemtoReplace[0].removeChild(el)
          } else {
            el.setAttribute('transform', 'scale(' + this.RENDER_OPTIONS.scale + ')')
          }
        }
      }
      // this.scaleSVG()
    },
    addData () {
      // LES CHOSES ECRITES PAR LELEVE
      const restValues = window.document.querySelectorAll('section.textWidgetAnnotation, section.buttonWidgetAnnotation, section.choiceWidgetAnnotation')
      restValues.forEach((value) => {
        if (value.children[0].type === 'checkbox' || value.children[0].type === 'radio') {
          value.children[0].checked = false
          value.children[0].value = false
        } else {
          value.children[0].value = null
        }
      })
      if (this.data) {
        const temp = JSON.parse(this.data)
        temp.forEach((element, index) => {
          const htelement = window.document.querySelector('[data-annotation-id="' + element.id + '"]')
          if (element.type === 'drawing') {
            const cleanSVG = element.value.replace(/\<(\?xml|(\!DOCTYPE[^\>\[]+(\[[^\]]+)?))+[^>]+\>/g, '')
            const file = new Blob([cleanSVG], { type: 'image/svg+xml' })
            const SVGElement = document.querySelector('#contentId')
            const widthRef = SVGElement.style.width
            const imageEnfant = window.document.createElement('img')
            const blobFile = URL.createObjectURL(file)
            imageEnfant.setAttribute('src', blobFile)
            imageEnfant.setAttribute('id', 'image-' + index)
            imageEnfant.setAttribute('style', 'position:absolute;top:0;opacity:0.85;')
            // scale:' + this.RENDER_OPTIONS.scale + ';')
            imageEnfant.classList.add('imageSVG')
            // imageEnfant.setAttribute('height', heightRef)
            SVGElement.appendChild(imageEnfant)
          } else if (element.type === 'groupMath') {
            element.value.objects.forEach((e, i) => {
              if (e.custom) {
                const cleanSVG = e.custom.mathSvgString.replace(/\<(\?xml|(\!DOCTYPE[^\>\[]+(\[[^\]]+)?))+[^>]+\>/g, '')
                
                const elemtoReplace = window.document.querySelectorAll('svg#svgannotate.annotationLayer')
                const canvasWidth = e.custom?.canvasWidth
                const ratio = elemtoReplace[0].width.baseVal.value/canvasWidth
                const br = e.custom?.br
                const tl = e.custom?.tl
                const top = e.top * ratio
                const left = e.left * ratio
                const newWidth = (br.x - tl.x) * ratio
                const newheigth = (br.y - tl.y) * ratio
                
                const file = new Blob([cleanSVG], { type: 'image/svg+xml' })
                const SVGElement = document.querySelector('#contentId')
                const widthRef = SVGElement.style.width
                const imageEnfant = window.document.createElement('img')
                imageEnfant.innerHTML = cleanSVG
                const blobFile = URL.createObjectURL(file)
                imageEnfant.setAttribute('src', blobFile)
                imageEnfant.setAttribute('id', 'image-' + index)
                imageEnfant.setAttribute('style', `z-index:10;position:absolute; top:${top}px; left:${left}px; width:${newWidth}px; heigth:${newheigth}px opacity:1;`)
                // scale:' + this.RENDER_OPTIONS.scale + ';')
                imageEnfant.classList.add('imageSVG')
                imageEnfant.setAttribute('width', widthRef)
                SVGElement.appendChild(imageEnfant)
                if(e.custom?.type === 'desmos') {
                  imageEnfant.addEventListener('click', () => {
                    if(this.origin === 'glossaire') {
                      this.$store.commit('layout/setShowDesmosPreview', true)
                      this.$store.commit('layout/setCorrection', true)
                      this.$store.commit('layout/setDesmosExpressions', element.value?.objects[i]?.custom?.desmosExpressions)
                    } else {
                      this.desmosExpressions = element.value?.objects[i].custom?.desmosExpressions
                      this.showDesmos = true
                    }
                  })
                let cursorText = null
                imageEnfant.addEventListener('mouseover', (event) => {
                  imageEnfant.style.border = "2px solid blue"
                  imageEnfant.style.cursor = "pointer"
                  let cursorText = document.createElement("div")
                  cursorText.textContent = "Cliquez ici pour afficher les fonctions Desmos"
                  cursorText.style.position = "absolute"
                  cursorText.style.left = `${event.pageX - 30}px`
                  cursorText.style.top = `${event.pageY + 20}px`
                  cursorText.style.zIndex = "9999999"
                  cursorText.style.background = "#E0FF9B"
                  cursorText.style.width = "155px"
                  cursorText.style.borderRadius = "4px"
                  cursorText.style.padding = "8px"
                  cursorText.style.fontFamily = "Arial, sans-serif"
                  cursorText.style.fontSize = "12px"
                  cursorText.style.color = "black"
                  document.body.appendChild(cursorText)
                  imageEnfant.addEventListener("mousemove", (event) => {
                    if (cursorText) {
                      cursorText.style.left = `${event.pageX - 30}px`
                      cursorText.style.top = `${event.pageY + 20}px`
                    }
                  })  
                  
                  imageEnfant.addEventListener("mouseout", () => {
                    if (cursorText) {
                      document.body.removeChild(cursorText)
                      cursorText = null
                    }
                    imageEnfant.style.border = "none"
                  })
                })
                }
              }
            })
          } else if (htelement && htelement.children[0]) {
            if (htelement.children[0].type === 'checkbox' || htelement.children[0].type === 'radio') {
              htelement.children[0].checked = element.value
            } else {
              htelement.children[0].value = element.value
            }
          }
        })
      }
    },
    // Hotspot color stuff
    HotspotColorStuff () {
      const self = this
      let hotspotColor = localStorage.getItem(`${self.RENDER_OPTIONS.documentId}/hotspot/color`) || 'red';
      let currentTarget;

      function handleAnnotationClick (target) {
        let type = target.getAttribute('data-pdf-annotate-type');
        if (['fillcircle', 'arrow'].indexOf(type) === -1) {
          return; // nothing to do
        }
        currentTarget = target;
        hotspotColor = currentTarget.getAttribute('stroke');

        UI.setArrow(10, hotspotColor);
        UI.setCircle(10, hotspotColor);

        let a = window.document.querySelectorAll('.hotspot-color .color');
        let b = window.document.querySelector('button .active-color');
        if (a.length > 0) {
          a.forEach((element) => {
            element.setAttribute('data-color', hotspotColor);
            element.style.background = hotspotColor;
          })
          // a.setAttribute('data-color', hotspotColor);
          b.setAttribute('data-color', hotspotColor);
          // a.style.background = hotspotColor;
        }
      }

      function handleAnnotationBlur (target) {
        if (currentTarget === target) {
          currentTarget = undefined;
        }
      }
      const elems = window.document.querySelectorAll('.hotspot-color')
      if (elems.length > 0) {
        elems.forEach((element) => {
          initColorPicker (element, hotspotColor, function(value) {
            if (value === hotspotColor) {
              return; // nothing to do
            }
            localStorage.setItem(`${self.RENDER_OPTIONS.documentId}/hotspot/color`, value);
            hotspotColor = value;

            UI.setArrow(10, hotspotColor);
            UI.setCircle(10, hotspotColor);

            if (!currentTarget) {
              return; // nothing to do
            }

            let type = currentTarget.getAttribute('data-pdf-annotate-type');
            let annotationId = currentTarget.getAttribute('data-pdf-annotate-id');
            if (['fillcircle', 'arrow'].indexOf(type) === -1) {
              return; // nothing to do
            }

            // update target
            currentTarget.setAttribute('stroke', hotspotColor);
            currentTarget.setAttribute('fill', hotspotColor);

            // update annotation
            PDFJSAnnotate.getStoreAdapter().getAnnotation(self.RENDER_OPTIONS.documentId, annotationId).then((annotation) => {
              annotation.color = hotspotColor;
              PDFJSAnnotate.getStoreAdapter().editAnnotation(self.RENDER_OPTIONS.documentId, annotationId, annotation);
            });
          });
        })
      }

      UI.addEventListener('annotation:click', handleAnnotationClick);
      UI.addEventListener('annotation:blur', handleAnnotationBlur);
    },

    // Text stuff
    TextStuff () {
      const self = this
      let textSize;
      let textColor;

      function initText() {
        let size = window.document.querySelector('.toolbar .text-size');
        [8, 9, 10, 11, 12, 14, 18, 24, 30, 36, 48, 60, 72, 96].forEach((s) => {
          size.appendChild(new Option(s, s));
        });

        setText(
          localStorage.getItem(`${self.RENDER_OPTIONS.documentId}/text/size`) || 18,
          localStorage.getItem(`${self.RENDER_OPTIONS.documentId}/text/color`) || '#000000'
        );
        setText(textSize, '#000000');
        // initColorPicker(document.querySelector('.text-color'), textColor, function(value) {
        //   setText(textSize, value);
        // });
      }

      function setText(size, color) {
        let modified = false;

        if (textSize !== size) {
          modified = true;
          textSize = size;
          localStorage.setItem(`${self.RENDER_OPTIONS.documentId}/text/size`, textSize);
          window.document.querySelector('.toolbar .text-size').value = textSize;
        }

        if (textColor !== color) {
          modified = true;
          textColor = color;
          localStorage.setItem(`${self.RENDER_OPTIONS.documentId}/text/color`, textColor);

          let selected = window.document.querySelector('.toolbar .text-color.color-selected');
          if (selected) {
            selected.classList.remove('color-selected');
            selected.removeAttribute('aria-selected');
          }

          selected = window.document.querySelector(`.toolbar .text-color[data-color="${color}"]`);
          if (selected) {
            selected.classList.add('color-selected');
            selected.setAttribute('aria-selected', true);
          }
        }

        if (modified) {
          UI.setText(textSize, textColor);
        }
      }

      function handleTextSizeChange(e) {
        setText(e.target.value, textColor);
      }

      window.document.querySelector('.toolbar .text-size').addEventListener('change', handleTextSizeChange);

      initText();
    },
    // Pen stuff
    PenStuff () {
      const self = this
      let penSize;
      let penColor;
      function initPen() {
        let size = window.document.querySelector('.pen-size');
        for (let i = 1; i < 21; i++) {
          size.appendChild(new Option(i, i));
        }

        setPen(
          localStorage.getItem(`${self.RENDER_OPTIONS.documentId}/pen/size`) || 5,
          localStorage.getItem(`${self.RENDER_OPTIONS.documentId}/pen/color`) || '#000000'
        );
        setPen(penSize, '#000000');
        // initColorPicker(document.querySelector('.pen-color'), penColor, function(value) {
        //   setPen(penSize, value);
        // });
      }

      function setPen(size, color) {
        let modified = false;

        if (penSize !== size) {
          modified = true;
          penSize = size;
          localStorage.setItem(`${self.RENDER_OPTIONS.documentId}/pen/size`, penSize);
          window.document.querySelector('.pen-size').value = penSize;
        }

        if (penColor !== color) {
          modified = true;
          penColor = color;
          localStorage.setItem(`${self.RENDER_OPTIONS.documentId}/pen/color`, penColor);

          let selected = window.document.querySelector('.toolbar .pen-color.color-selected');
          if (selected) {
            selected.classList.remove('color-selected');
            selected.removeAttribute('aria-selected');
          }

          selected = window.document.querySelector(`.toolbar .pen-color[data-color="${color}"]`);
          if (selected) {
            selected.classList.add('color-selected');
            selected.setAttribute('aria-selected', true);
          }
        }

        if (modified) {
          UI.setPen(penSize, penColor);
        }
      }

      function handlePenSizeChange(e) {
        setPen(e.target.value, penColor);
      }

      window.document.querySelector('.pen-size').addEventListener('change', handlePenSizeChange);

      initPen();
    },
    // Toolbar buttons
    ToolbarButtons (limited) {
      const self = this
      let tooltype = localStorage.getItem(`${self.RENDER_OPTIONS.documentId}/tooltype`) || 'cursor';
      if (tooltype) {
        setActiveToolbarItem(tooltype, window.document.querySelector(`.toolbar button[data-tooltype=${tooltype}]`));
      }

      function setActiveToolbarItem(type, button) {
        let active = window.document.querySelector('.toolbar button.active');
        if (active) {
          if (tooltype !== type) {
            active.classList.remove('active');
            if (tooltype === 'math') {
              UI.disableMathText();
            }
          }
          switch (type) {
            case 'cursor':
              UI.disableEraser();
              UI.disablePen();
              UI.disableText();
              UI.disableRect();
              UI.disableCircle();
              UI.disableArrow();
              UI.disablePoint();
              UI.disableMathText();
              UI.enableEdit();
              break;
            case 'eraser':
              UI.disableEdit();
              UI.disablePen();
              UI.disableText();
              UI.disableRect();
              UI.disableCircle();
              UI.disableArrow();
              UI.disablePoint();
              UI.disableMathText();
              UI.enableEraser();
              break;
            case 'draw':
              UI.disableEraser();
              UI.disableEdit();
              UI.disableText();
              UI.disableRect();
              UI.disableCircle();
              UI.disableArrow();
              UI.disablePoint();
              UI.disableMathText();
              UI.enablePen();
              break;
            case 'arrow':
              UI.disablePen();
              UI.disableEraser();
              UI.disableEdit();
              UI.disableText();
              UI.disableMathText();
              UI.disableRect();
              UI.disableCircle();
              UI.disablePoint();
              UI.enableArrow();
              break;
            case 'text':
              UI.disableArrow();
              UI.disablePen();
              UI.disableEraser();
              UI.disableMathText();
              UI.disableEdit();
              UI.disableRect();
              UI.disableCircle();
              UI.disablePoint();
              UI.enableText();
              break;
            case 'math':
              UI.disableText();
              UI.disableArrow();
              UI.disablePen();
              UI.disableEraser();
              UI.disableEdit();
              UI.disableRect();
              UI.disableCircle();
              UI.disablePoint();
              UI.enableMathText();
              break;
            case 'point':
              UI.disableMathText();
              UI.disableArrow();
              UI.disablePen();
              UI.disableEraser();
              UI.disableEdit();
              UI.disableRect();
              UI.disableCircle();
              UI.enablePoint();
              break;
            case 'area':
            case 'highlight':
            case 'strikeout':
              UI.disableMathText();
              UI.disableArrow();
              UI.disablePen();
              UI.disableEraser();
              UI.disablePoint();
              UI.disableEdit();
              UI.disableRect();
              UI.disableCircle();
              UI.enableRect();
              break;
            case 'circle':
            case 'emptycircle':
            case 'fillcircle':
              UI.disableMathText();
              UI.disableArrow();
              UI.disablePen();
              UI.disablePoint();
              UI.disableEraser();
              UI.disableEdit();
              UI.disableRect();
              UI.enableCircle();
              break;
          }
        }

        if (button) {
          button.classList.add('active');
        }
        let zone = window.document.getElementById('content-wrapper')
        if (tooltype !== type) {
          localStorage.setItem(`${self.RENDER_OPTIONS.documentId}/tooltype`, type);
          zone.classList.add(type)
          zone.classList.remove(tooltype)
        } else {
          zone.classList.add(type)
        }
        tooltype = type;
        switch (type) {
          case 'cursor':
            UI.enableEdit();
            break;
          case 'eraser':
            UI.enableEraser();
            break;
          case 'draw':
            if (self.activeMenu !== 'draw') {
              UI.enablePen();
            }
            break;
          case 'arrow':
            UI.enableArrow();
            break;
          case 'text':
            UI.enableText();
            break;
          case 'math':
            UI.enableMathText();
            break;
          case 'point':
            UI.enablePoint();
            break;
          case 'area':
          case 'highlight':
          case 'strikeout':
            UI.enableRect(type);
            break;
          case 'circle':
          case 'emptycircle':
          case 'fillcircle':
            UI.enableCircle(type);
            break;
        }
      }

      function handleToolbarClick(e) {
        if (e.target.nodeName === 'BUTTON') {
          setActiveToolbarItem(e.target.getAttribute('data-tooltype'), e.target);
        }
      }

      window.document.querySelector('.toolbar').addEventListener('click', handleToolbarClick);
    },
    resizeDocument (state) {
      const self = this
      let valtemp = this.RENDER_OPTIONS.scale
      if (state === 'down') {
        if (valtemp > 0.25) {
          valtemp-= 0.25
        }
      } else if (state === 'up') {
        if (valtemp < 2) {
          valtemp+= 0.25
        }
      }
      let scale = parseFloat(valtemp, 10);
      this.RENDER_OPTIONS.scale = parseFloat(valtemp, 10);
      localStorage.setItem(`${self.RENDER_OPTIONS.documentId}/scale`, this.RENDER_OPTIONS.scale);
      this.render()
    },
    // Scale/rotate
    ScaleAndRotate () {
      const self = this
      function setScaleRotate(scale, rotate) {
        scale = parseFloat(scale, 10);
        rotate = parseInt(rotate, 10);

        if (self.RENDER_OPTIONS.scale !== scale || self.RENDER_OPTIONS.rotate !== rotate) {
          self.RENDER_OPTIONS.scale = scale;
          self.RENDER_OPTIONS.rotate = rotate;

          localStorage.setItem(`${self.RENDER_OPTIONS.documentId}/scale`, self.RENDER_OPTIONS.scale);
          localStorage.setItem(`${self.RENDER_OPTIONS.documentId}/rotate`, self.RENDER_OPTIONS.rotate % 360);

          self.render()
        }
      }

      function handleScaleChange (value) {
        setScaleRotate(value, self.RENDER_OPTIONS.rotate);
      }

      // function handleScaleChange (e) {
      //   setScaleRotate(e.target.value, self.RENDER_OPTIONS.rotate);
      // }

      // function handleRotateCWClick () {
      //   setScaleRotate(self.RENDER_OPTIONS.scale, self.RENDER_OPTIONS.rotate + 90);
      // }

      // function handleRotateCCWClick () {
      //   setScaleRotate(self.RENDER_OPTIONS.scale, self.RENDER_OPTIONS.rotate - 90);
      // }

      window.document.querySelector('.toolbar select.scale').value = self.RENDER_OPTIONS.scale;
    },

    // Clear toolbar button
    ClearToolbarButton () {
      const self = this
      function handleClearClick () {
        if (confirm('Voulez-vous réellement supprimer vos corrections?')) {
          for (let i = 0; i < self.NUM_PAGES; i++) {
            window.document.querySelector(`div#pageContainer${i + 1} svg#svgannotate.annotationLayer`).innerHTML = '';
          }

          localStorage.removeItem(`${self.RENDER_OPTIONS.documentId}/annotations`);
          self.$emit('deleteAll')
        }
      }
      window.document.querySelector('a.clear').addEventListener('click', handleClearClick);
    },
    saveComment (target) {
      let commentList = window.document.querySelector('#comment-wrapper .comment-list-container');
      function insertComment(comment) {
        if (comment.html) {
          let child = window.document.createElement('div');
          child.className = 'comment-list-item';
          child.innerHTML = comment.html;
          MathLive.makeMathField(child, {
            locale: 'fr',
            readOnly: true,
            customVirtualKeyboardLayers: CUSTOM_KEYBOARD_LAYER,
            customVirtualKeyboards: { 'custom-keyboard': { label: '123', tooltip: 'Numérique', layer: 'custom-layer' } },
            virtualKeyboards: 'custom-keyboard symbols'
          });
          // DEGUEU ON VIRE LE TEXT AREA Y A SUREMENT UN MEILLEUR MOYEN
          if (child.children && child.children.length > 0) {
            for (let i = 0; i < child.children.length; i++) {
              if (child.children[i].className === 'ML__textarea') {
                child.children[i].remove();
                i = child.children.length;
              }
            }
          }
          commentList.appendChild(child);
        }
      }
      const element = document.querySelector('#pdf-annotate-edit-overlay')
      let documentId = this.RENDER_OPTIONS.documentId;
      let annotationId = element.getAttribute('data-target-id');
      let commentForm = window.document.querySelector('#comment-wrapper .comment-list-form__wrapper');
      let commentMathText = commentForm.querySelector('#mathComm');
      let commentNormalText = commentForm.querySelector('#normalComm');
      if (this.mathKeyboard) {
          if (commentMathText.getValue()) {
            // const elem = window.document.getElementById('annomain');
            // on emets la creation du commentaire
            this.$emit('submitComment', { id: documentId, annotation: annotationId, text: commentMathText.getValue().trim() })
            PDFJSAnnotate.getStoreAdapter().addComment(documentId, annotationId, commentMathText.getValue().trim())
              .then(insertComment)
              .then(() => {
                commentMathText.setValue('');
                commentMathText.focus();
              });
          }
          return false;
      } else {
        // commentForm.onsubmit = function(e) {
        if (commentNormalText && commentNormalText.value) {
          // const elem = window.document.getElementById('annomain');
          // on emets la creation du commentaire
          this.$emit('submitComment', { id: documentId, annotation: annotationId, text: commentNormalText.value.trim() })
          PDFJSAnnotate.getStoreAdapter().addComment(documentId, annotationId, commentNormalText.value.trim())
            .then(insertComment)
            .then(() => {
              commentNormalText.value = '';
              commentNormalText.focus();
            });
        }
        return false;
        // };
      }
    },
    // Comment stuff
    CommentStuff () {
      const self = this
      let commentList = window.document.querySelector('#comment-wrapper .comment-list-container');
      let commentForm = window.document.querySelector('#comment-wrapper .comment-list-form__wrapper');
      let commentMathText = commentForm.querySelector('#mathComm');
      let commentNormalText = commentForm.querySelector('#normalComm');
      function supportsComments(target) {
        let type = target.getAttribute('data-pdf-annotate-type');
        return ['point', 'highlight', 'area'].indexOf(type) > -1;
      }

      function insertComment(comment) {
        if (comment.html) {
          let child = window.document.createElement('div');
          child.className = 'comment-list-item';
          child.innerHTML = comment.html;
          MathLive.makeMathField(child, {
            locale: 'fr',
            readOnly: true,
            customVirtualKeyboardLayers: CUSTOM_KEYBOARD_LAYER,
            customVirtualKeyboards: { 'custom-keyboard': { label: '123', tooltip: 'Numérique', layer: 'custom-layer' } },
            virtualKeyboards: 'custom-keyboard symbols'
          });
          // DEGUEU ON VIRE LE TEXT AREA Y A SUREMENT UN MEILLEUR MOYEN
          if (child.children && child.children.length > 0) {
            for (let i = 0; i < child.children.length; i++) {
              if (child.children[i].className === 'ML__textarea') {
                child.children[i].remove();
                i = child.children.length;
              }
            }
            // const temp = child.childrens.find(e => e.className === 'ML__textarea')
            // if (temp) {
            //   temp.remove();
            // }
          }
          commentList.appendChild(child);
        }
      }
      function handleAnnotationClick(target) {
        this.activeTarget = target
        if (supportsComments(target)) {
          let documentId = target.parentNode.getAttribute('data-pdf-annotate-document');
          let annotationId = target.getAttribute('data-pdf-annotate-id');
          this.documentId = documentId;
          this.annotationId = annotationId;
          PDFJSAnnotate.getStoreAdapter().getComments(documentId, annotationId).then((comments) => {
            commentList.innerHTML = '';
            commentForm.style.display = '';
            const activeComment = commentNormalText || commentMathText
            activeComment.focus();

            comments.forEach(insertComment);
          });
        }
      }

      function handleAnnotationBlur(target) {
        if (supportsComments(target)) {
          commentList.innerHTML = '';
          commentForm.style.display = 'none';
          commentForm.onsubmit = null;

          insertComment({html: 'Aucun commentaire affiché/disponible'});
        }
      }

      UI.addEventListener('annotation:click', handleAnnotationClick);
      UI.addEventListener('annotation:blur', handleAnnotationBlur);

      UI.setArrow(10, 'red');
      UI.setCircle(10, 'red');
    }
  }
}
</script>

<style scoped>
  .pdfViewer .canvasWrapper {
    box-shadow: 0 0 3px #bbb;
  }
  .pdfViewer .page {
    margin-bottom: 10px;
  }
  #content-wrapper {
    position: absolute;
    top: 0;
    left: 0;
    right: 250px;
    bottom: 0px;
    overflow: auto;
    transition: all 0.15s ease-in;
  }
  #content-wrapper.full-height {
    bottom: 0px;
  }
  #content-wrapper.fullsize {
    right: 0px;
  }
  .drawer-button {
    position: absolute;
    top: 75px;
    right: calc(100% + 30px);
    height: 50px;
    width: 50px;
    border-radius: 30px;
    background-color: black;
    color: white;
    outline: none;
    border: none;
    font-size: 24px;
  }
  #comment-wrapper {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0px;
    width: 250px;
    background: white;
    /* border-left: 1px solid #d0d0d0; */
    transform: translateX(100%);
    transition: all 0.15s ease-in;
    max-height: 100vh;
  }
  #comment-wrapper.full-height {
    bottom: 0px;
    max-height: 100vh;
  }
  #comment-wrapper.active {
    transform: translateX(0%);
  }
  #comment-wrapper .comment-list h4 {
    margin: 0;
    padding: 10px 0;
    position: sticky;
    top: 0;
    font-size: 20px;
  }
  #comment-wrapper .comment-list {
    font-size: 12px;
    height: 100%;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    padding: 10px;
  }
  #comment-wrapper .comment-list-item {
    border-bottom: 1px solid #d0d0d0;
  }
  #comment-wrapper .comment-list-container {
    margin-top: 10px;
  }
  #comment-wrapper .comment-list-form__wrapper {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: lightgrey;
  }
  #comment-wrapper .comment-list-form__wrapper.hidden-content {
    opacity: 0;
    pointer-events: none;
  }
  #comment-wrapper .comment-list-form__wrapper form fieldset {
    border: 0;
    margin: 0;
    min-width: 0;
    padding: 0.01em 0 0 0;
  }
  #comment-wrapper .comment-list-form__wrapper .comment-list-form {
    /* padding: 10px 10px; */
  }
  #comment-wrapper .comment-list-form__wrapper .comment-list-form textarea {
    padding: 5px;
    width: calc(100% - 20px);
    background-color: white;
    border: none;
    margin: 0 10px 10px 10px;
    border-radius: 0 0 10px 10px;
  }
  #comment-wrapper .comment-list-form__wrapper .comment-list-form #mathComm {
    padding: 10px;
    width: calc(100% - 20px);
    background-color: white;
    margin: 0 10px 10px 10px;
    border-radius: 0 0 10px 10px;
  }
  #comment-wrapper .comment-list-form__wrapper .input-type-toggle {
    padding: 10px;
    width: calc(100% - 20px);
    border: none;
    outline: none;
    background-color: rgba(0,0,0,1);
    color: white;
    margin: 15px 10px 0 10px;
    border-radius: 10px 10px 0 0;
    transition: all 0.15s ease-in;
  }
  #comment-wrapper .comment-list-form__wrapper .input-type-toggle:hover {
    background-color: rgba(0,0,0,0.75);
  }
  #comment-wrapper .comment-list-form__wrapper .input-type-toggle span {
    margin-right: 10px;
  }
  #comment-wrapper .comment-list-form__wrapper .input-type-answer {
    padding: 20px 10px;
    width: 100%;
    border: none;
    outline: none;
    background-color: #2196F3;
    color: white;
    font-size: 16px;
  }


</style>
