<template>
  <div>
    <div id="titreContenu" v-bind:style="darktheme ? 'color:white' : ''">
      <!--      <select v-show="(contenuCliqueProvenance === 'banque'
            || contenuCliqueProvenance === 'perso')

             && versionMax > 1" v-model="versionChoisie" v-on:change="changerVersion" >-->
      <div id="typeEtSource">
        Type : {{typeContenu}}<br>

        Source : {{sourceContenu}}
      </div>
      <div id="notePopularite">
        Note version : {{noteContenu}}<br>
        Popularité : {{populariteContenu}}<br>
      </div>
      <span id="tagsLibres" v-on:click="modifierTags">{{ titreModifierTags }}</span>


      <div id="modifTitre">
        <div id="changerTitre">
          <label v-if="sourceContenu !== 'moodle'">Titre du contenu : </label>
          <label v-else>Nom de la question : </label>
          <br>
          <select v-show="contenuCliqueProvenance === 'perso' && versionMax > 1" v-model="versionChoisie" v-on:change="changerVersion"
                  style="margin-right: 5px; background: none; border: none" >
            <option v-for="i in versionMax" v-bind:key="i"> {{i}}</option>
          </select>
          <input type="text" id="titreDuContenu" placeholder="titre du contenu" style="width: 15vw; outline: none; border: none; margin-right: 1vw"  v-model="titreContenu">
        </div>
        <div id="voirNote">
          <button style="margin-left: 10px; background: floralwhite; border: none" v-show="contenuCliqueProvenance === 'tiers' && !notePresente" id="noterContenu">{{ messageNoter }}</button>
          <b-popover target="noterContenu" triggers="click" placement="bottom">
            <star-rating @rating-selected ="setRating" v-model="rating" :read-only="notePresente" :show-rating="false" :increment=0.5 :star-size=25 />
          </b-popover>

          <star-rating id="etoiles" v-show="notePresente" @rating-selected ="setRating" v-model="rating" :read-only="notePresente"
                       :show-rating="false" :increment=0.5 :star-size=25 style="margin-right: 0.1vw" />
        </div>
      </div>

      <div id="actionsContenu">
        <!--        <button class="boutonAction" v-on:click="actionContenu('supprimer')">Supprimer</button>-->
        <span class="boutonAction" v-if="contenuCliqueProvenance !== 'perso' && contenuCliqueProvenance !== 'tiers'" v-on:click="actionContenu('supprimer')" id="supprimerContenu"></span>
        <span class="boutonAction" v-else v-on:click="actionContenu('supprimer')" id="supprimerContenuSolo"></span>
        <!--        <button class="boutonAction" v-show="contenuCliqueProvenance !== 'maj' && contenuCliqueProvenance === 'en-cours' &&
              contenuClique.origine === 'tiers' && contenuClique.anonyme !== 'oui'" v-on:click="actionContenu('publier')">Publier le contenu</button>-->
        <span  class="boutonAction" v-show="contenuCliqueProvenance !== 'maj' && contenuCliqueProvenance === 'en-cours' &&
      contenuClique.origine === 'tiers' && contenuClique.anonyme !== 'oui'" v-on:click="actionContenu('publier')" id="publierContenu">publier contenu</span>
        <!--        <button class="boutonAction" v-show="contenuCliqueProvenance !== 'maj' && contenuCliqueProvenance === 'en-cours' &&
              (contenuClique.origine === 'perso' || contenuClique.anonyme === 'oui')"
                        v-on:click="actionContenu('validerModification')">Valider la modification</button>-->
        <span class="boutonAction" v-show="contenuCliqueProvenance !== 'maj' && contenuCliqueProvenance === 'en-cours' &&
      (contenuClique.origine === 'perso' || contenuClique.anonyme === 'oui')"
              v-on:click="actionContenu('validerModification')" id="validerContenu">valider contenu</span>
        <span class="boutonAction" v-show="sourceContenu === 'moodle'" v-on:click="actionContenu('exporter')"
              id="exporterContenu">Exporter</span>
      </div>
    </div>
    <br>
    <div class="mavonEditor" v-show="!isModeTag && sourceContenu !== 'moodle'">

      <mavon-editor  :language="'fr'" style="position: static; height: 78vh; margin-top: -0.77%" v-model="texteAffiche"/>
    </div>
    <TagsLibres v-show="isModeTag" v-bind:contenu="this.contenuClique" v-bind:auteur="auteur" @actionTagLibre="actionTagLibre"
                style="position: static; height: 78vh; margin-top: -0.77%" v-bind:darktheme="darktheme" @chargerTagsLibres="chargerTagsLibres"
                v-bind:tagLibreAssocie="tagLibreAssocie" v-bind:provenance="contenuCliqueProvenance"
                v-bind:rechargerTagsLibres="rechargerTagsLibres" @tags="nouveauxTags"></TagsLibres>

    <Edit_Contenus @actionMoodle="actionMoodle" v-show="!isModeTag && sourceContenu === 'moodle'" v-bind:darktheme="darktheme"
                   v-bind:idContenu="idContenu" v-bind:source="sourceContenu" v-bind:provenance="contenuCliqueProvenance"
                   v-bind:changerVersion="changerDeVersion" v-bind:versionCourante="this.versionMax"></Edit_Contenus>

    <Previsualiser_Moodle v-bind:changerVersion="changerDeVersion" v-bind:source="'pas moodle'" v-show="false"></Previsualiser_Moodle>

    <div class="markdown" v-show="sourceContenu !== 'moodle'">
      <br>
      <button id="validerModif" v-on:click="action('valider')" v-if="versionMax === versionChoisie">modifier </button>
      <button id="retourArriere" v-on:click="action('arriere')"> revenir en arrière</button>

    </div>
    <star-rating v-show="false"/>
  </div>
</template>

<script>

import Service from "../service/Service";
import StarRating from 'vue-star-rating'
import TagsLibres from "../TagsLibres";
import Edit_Contenus from "./moodle/Edit_Contenus";
import Previsualiser_Moodle from "@/Previsualiser_Moodle";


export default {
  name: "Modifier_Contenu",
  components: {
    Previsualiser_Moodle,
    Edit_Contenus,
    TagsLibres,
    StarRating
  },
  props: {
    // le texte du contenu cliqué
    texteDuContenu: {},
    // l'auteur qui effectue la modification (l'auteur du contenu en cours)
    auteur: {},
    // la provenance (perso, tiers, en-cours)
    contenuCliqueProvenance: {},
    // la version du contenu cliqué
    contenuCliqueVersion: {},
    // le contenu clique
    contenuClique: {},
    // Signal d'activation ou non du theme sombre
    darktheme: {},
    // Récupération d'un tag libre ajouté
    tagLibreAssocie: {},
    // signal pour recharger les Tags Libres
    rechargerTagsLibres: {}
  },
  data: function () {
    return {
      contenu: '',
      versionChoisie: 0,
      titreContenu: '',
      isContenuRefuse: false,
      versionMax: 0,
      rating: 0,
      notePresente: false,
      messageNoter: "noter",
      populariteContenu: 0,
      noteContenu: 0,
      isModeTag: false,
      titreModifierTags: "modifier Tags",
      typeContenu: '',
      sourceContenu: '',
      idContenu: '',
      texteAffiche: '',
      changerDeVersion: ''
    }
  },
  methods: {
    /**
     * @vuese
     * Gestion de l'action choisie par l'utilisateur : soit valider une modification de l'intérieur du contenu, soit revenir en arrière
     */
    action: function (actionChoisie) {
      this.isModeTag = false
      this.questionParsee = ''
      if (actionChoisie === 'valider'){

        if (this.sourceContenu === 'moodle'){
          console.log("Je modifie un moodle")
        } else {
          // evenement de modification du texte d'un contenu
          // @arg l'action choisie, ici 'valider'
          // @arg le texte modifié
          this.$emit("choixModif", {action: actionChoisie, nouveauTexte: this.texteAffiche, titre: this.titreContenu})
        }
      } else {
        // evenement de retour en arrière vers Consulter_COntenu
        // @arg l'action choisie, ici 'arriere'
        this.$emit("choixModif", {action: actionChoisie})

      }


    },
    /**
     * @vuese
     * Si on change de version on recharge le texte du contenu
     */
    changerVersion: function () {
      let that = this
      if (this.sourceContenu !== 'moodle') {
        Service.recupererTexteVersionContenu(JSON.stringify(this.contenuClique._id), this.versionChoisie).then(
            function (response) {
              that.texteAffiche = response.data
              // alert(response.data)
            }
        )
      } else {
        this.changerDeVersion = this.versionChoisie
      }
    },
    /**
     * @vuese
     * Dès qu'une action est sélectionnée, la renvoie à Volet_Base
     */
    actionContenu: function (action) {
      // Dès qu'une action est sélectionnée, la renvoie à Volet_Base
      // @arg action l'action choisie
      // @arg contenu le contenu cliqué
      // @arg le texte associé au contenu (sert potentiellement à rien)

      this.$emit("actionContenu", {action: action, contenu: this.contenuClique, texte: this.texteDuContenu})
    },
    /**
     * @vuese
     * Fonction de récupération de la note mise par l'utilisateur
     */
    setRating: function () {
      let that = this
      let data = {
        id_contenu: JSON.stringify(this.contenuClique._id),
        note: this.rating,
        auteur: this.auteur,
        version: this.contenuClique.version
      }
      Service.noterContenu(data).then(function (response) {
        document.getElementById('noterContenu').click()
        that.notePresente = true
        that.messageNoter = "Voir votre note"
        let notes = JSON.parse(response.data)

        that.$emit("majMoyenne", {
          id: that.contenuClique._id,
          note: notes[0],
          nbreNotes: notes[1],
          notePerso: that.rating
        })
      })
    },
    /**
     * Déclencheur du mode "edition de tag"
     */
    modifierTags: function () {
      this.isModeTag = !this.isModeTag
      if (this.isModeTag){
        this.titreModifierTags = "modifier contenu"
      } else {
        this.titreModifierTags = "modifier tags"
      }
    },
    /**
     * @vuese
     * ajout ou suppression d'un tag à destination de Volet_Base
     */
    actionTagLibre: function (event) {
      // on est dans le cadre de la suppression d'un tag
      if(event.creation === undefined){
        this.$emit("actionTagLibre", {suppression: event.suppression, id_contenu: event.id_contenu})
      }
      // on est dans le cadre de l'ajout d'un tag
      else {
        this.$emit("actionTagLibre", {creation: event.creation, id_contenu: event.id_contenu})
      }
    },
    /**
     * @vuese
     * Permet de passer le signal pour charger le composant "GererTagsLibres"
     */
    chargerTagsLibres: function () {
      this.$emit("chargerTagsLibres")
    },
    actionMoodle: function (event) {

      if (this.contenuCliqueProvenance === 'perso'){
        let data = {id_contenu: JSON.stringify(this.idContenu) }
        Service.recalibrerGit(data)
        this.changerDeVersion = this.versionMax
        this.versionChoisie = this.versionMax
      }
      if (event.action === 'arriere'){

        this.$emit("choixModif", {action: event.action})

      }
      else
        this.$emit("choixModif", {action: event.action, questionParsee: event.questionParsee, titre: this.titreContenu})
    },
    /**
     * @vuese
     * Recup des nouveaux tags fixes
     */
    nouveauxTags: function (event) {
      this.$emit("tags", {tags: event.tagsChoisis})
    }


  },
  computed: {
    /**
     * @vuese
     * Fonction de calcul de la note globale d'un contenu (en fonction de sa version)
     */
    calculerNoteContenu: function() {

      if (this.sourceContenu !== "moodle" && this.contenuCliqueProvenance !== "") {
        console.log (parseInt(this.versionChoisie) + " " + this.versionMax)
        if (parseInt(this.versionChoisie) !== this.versionMax) {
          console.log("Ici")
          for (let it in this.contenuClique.historique) {
            if (this.contenuClique.historique[it].numero === parseInt(this.versionChoisie)) {
              if (this.contenuClique.historique[it].note === 0) {
                return 0
              }
              return (this.contenuClique.historique[it].note / this.contenuClique.historique[it].nbreNotes).toFixed(2)
            }
          }
          return -1
        } else {
          console.log("Là")
          if (this.contenuClique.versionEnCours.note === 0) {
            return 0
          }
          return (this.contenuClique.versionEnCours.note / this.contenuClique.versionEnCours.nbreNotes).toFixed(2)
        }
      } else {
        return this.contenuClique.moyenne
      }
    },
  },
  watch: {
    /**
     * @vuese
     * Dès qu'un contenu est chargé on l'analyse pour "habiller" la page
     */
    contenuClique: function () {


      if (this.contenuClique !== []) {
        this.titreContenu = this.contenuClique.titre
        this.noteContenu = this.contenuCliqueProvenance !== 'en-cours' ? this.calculerNoteContenu : this.contenuClique.moyenne
        this.typeContenu = this.contenuClique.type
        this.sourceContenu = this.contenuClique.source
        this.populariteContenu = this.contenuClique.popularite
        this.idContenu = this.contenuClique._id
        this.texteAffiche = this.texteDuContenu
        this.isContenuRefuse = Object.prototype.hasOwnProperty.call(this.contenuClique, 'refuse')

        if (this.contenuCliqueProvenance === 'perso') {
          this.versionMax = this.contenuClique.versionEnCours.numero
          alert(this.versionMax)
          this.versionChoisie = this.versionMax
        } else {
          this.versionChoisie = this.contenuClique.version
          this.versionMax = this.versionChoisie
        }

        let that = this

        if (this.contenuCliqueProvenance !== 'banque'){
          Service.recupererNoteContenu(JSON.stringify(this.contenuClique._id), this.auteur, this.versionChoisie).then(function (result) {
            let nombre = result.data
            console.log("nombre : " + nombre + " " + typeof (nombre))
            if (nombre !== '-') {
              //nombre = JSON.parse(nombre)
              //that.rating = nombre.note
              that.rating = parseInt(nombre)
              that.notePresente = true
            }
          })
        }
      }
    },
    /**
     * @vuese
     * Si on change de version on recalcule la note
     */
    versionChoisie: function () {
      this.noteContenu = this.calculerNoteContenu
    },

  }
}

</script>

<style scoped>
div {
  text-align: center;
}
button {
  height: auto;
  width: auto;
}

#tagsLibres {
  margin: 20px 10px;
  flex-basis: 9%;

}

#validerModif {
  margin-right: 5px;
  margin-bottom: 10px;
}

#titreContenu {
  margin-left: 5px;
  text-align: center;
  align-content: center;
  display: flex;
  /*margin: 0 auto -15px;*/
}

#typeEtSource, #notePopularite {
  margin-top: 10px;
  flex-basis: 9%;
  margin-bottom: 10px;

}



#actionsContenu {
  margin-top: 20px;
  flex-basis: 25%;
}

#modifTitre {
  margin-top: 5px;
  flex-basis: 43%;
  margin-right: 5px;
  display: flex;
  justify-content: center;
  margin-bottom: 5px;
}

#noterContenu {
  margin-left: 5px;
}

#changerTitre {
  align-items: center;
  position: absolute;
}

#voirNote {
  margin-left: 400px;
  margin-top: 24px;
  align-items: inherit;
  position: relative
}

.boutonAction {
  margin-right: 2px;
}

#supprimerContenuSolo::before {
  content: "\01F5D1";
  font-size: 20px;

  /*  border-right: 1px solid black;
    margin-right: 10px;
    padding-right: 10px;*/
}

#supprimerContenuSoloDark::before {
  content: "\01F5D1";
  color: transparent;
  text-shadow: 0 0 0 white;
  font-size: 20px;

}

#supprimerContenu::before {
  content: "\01F5D1";
  border-right: 1px solid black;
  margin-right: 10px;
  padding-right: 10px;
  font-size: 20px;

}

#supprimerContenuDark::before {
  content: "\01F5D1";
  color: transparent;
  text-shadow: 0 0 0 white;
  border-right: 1px solid black;
  margin-right: 10px;
  padding-right: 10px;
  font-size: 20px;

}


#validerContenu::before {
  content: "\2712";
  margin-right: 5px;
}

#publierContenuDark::before {
  content: "\01F4F0";
  margin-right: 5px;
  color: transparent;
  text-shadow: 0 0 0 white;
}

#validerContenuDark::before {
  content: "\2712";
  margin-right: 5px;
  color: transparent;
  text-shadow: 0 0 0 white;
}

#publierContenu::before {
  content: "\01F4F0";
  margin-right: 5px;
}


#tagsLibres::before {
  content: "\270F ";
  transform: rotate(180deg);
  padding-right: 5px;
  margin-right: 5px;
  /*  left: 350px;
    position: absolute;*/
}

#exporterContenu::before {
  content: "\01F4F0";
  margin-right: 5px;
  border-left: 1px solid black;
  padding-left: 10px;
  margin-left: 10px;

}

#etoiles {
  margin-left: 10px;
}

</style>