<!----------------------------------------------------
	File:  ResearcherProfile.vue
	Author: Maxime Bartha
	Scope: Extension Publicatons scientifiquess
	Description: Researcher Profile Page containing his articles and his statistics
----------------------------------------------------->

<script setup>
import { ref, reactive } from "vue";
import FilterComponent from "@/Apps/ScientificPublications/FilterComponent.vue";
import ArticleComponent from "@/Apps/ScientificPublications/ResearchComponent.vue";
import {fetchResearcher, fetchResearches, fetchStats, addView, getFile} from "@/rest/ScientificPublications/ResearcherProfile.js";
const input = ref("");
const statsOf = ref("");
const statsBy = ref("");
const isFilterOpened = ref(false);
const isResearchOpened = ref(false);
const articleToDisplay = ref(Object)
const filters = ref([]);
let chart;

const researchList = ref(await fetchResearches(1));
//todo changer dynamiquement le 1 ici en fct de sur quel profil on est
const researcher = ref(await fetchResearcher(1));
const stats = ref(await fetchStats(1))

const props = defineProps({
  researcherId: ref(), //int
  filters: ref([""]),
});

const openFilter = () => {
  isFilterOpened.value = true;
};
const closeFilter = () => {
  isFilterOpened.value = false;
};
const submitFilters = ()=>{
}
const openResearch = (article) => {
  isResearchOpened.value = true;
  articleToDisplay.value = article;
}

const closeResearch = () => {
  isResearchOpened.value =false;
  articleToDisplay.value = null;
}

const downloadBibTex = (research) => {
  getFile(research.bibTexLocation)
}

const downloadArticle = (research) => {
  addView(research.pdfLocation)
  getFile(research.pdfLocation)
}

function downloadCoAuthors(){
  const data = JSON.stringify(researcher.value);
  const blob = new Blob([data], {type:"application/json"});
  return URL.createObjectURL(blob);
}


function searchInList(list, searchInput) {
  let retList = []
  for (let i = 0; i < list.length; i++) {
    if (lDistance(list[i].title, searchInput) < 10 || list[i].title.toUpperCase().indexOf(searchInput.toUpperCase()) > -1){
      retList.push(list[i])
    }
  }
  return retList
}

function lDistance(s,t){
  if (!s.length) return t.length;
  if (!t.length) return s.length;
  const arr = [];
  for (let i = 0; i <= t.length; i++) {
    arr[i] = [i];
    for (let j = 1; j <= s.length; j++) {
      arr[i][j] =
          i === 0
              ? j
              : Math.min(
                  arr[i - 1][j] + 1,
                  arr[i][j - 1] + 1,
                  arr[i - 1][j - 1] + (s[j - 1] === t[i - 1] ? 0 : 1)
              );
    }
  }
  return arr[t.length][s.length];
}

const options = reactive({
    backgroundColor:null,
    theme: "light2",
    animationEnabled: true,
    title: {
      fontColor: "white",
      text : "please select options",
    },
    data: [
      {
        type: "pie",
        indexLabel: "{label} (#percent%)",
        yValueFormatString: "#,##0",
        indexLabelFontColor: "white",
        toolTipContent:
          "<span style='\"'color: {color};'\"'>{label}</span> {y}(#percent%)",
      }]
	});

function update(){
  options.title = {
    fontColor: "white",
    text: statsOf.value + " By "+ statsBy.value,
  }
 let index = (statsOf.value === "views"?0:(statsOf.value === "researches"?3:6)) + (statsBy.value ==="years"?0:(statsBy.value==="months"?1:2))

  if (statsOf.value !== "" && statsBy.value !== "")
    options.data[0].dataPoints = stats.value[index]


  options.title.text = statsOf.value + " By "+ statsBy.value;
  chart.render();
}
</script>

<template>
  <div id="main">
    <FilterComponent :isOpen="isFilterOpened" :allArticles="researchList" @modal-close="closeFilter" @submit="submitFilters()"></FilterComponent>
    <ArticleComponent :article="articleToDisplay" :isOpen="isResearchOpened" :manage="false" @modal-close="closeResearch" @downloadPdf="downloadArticle(articleToDisplay)" @downloadBibTex="downloadBibTex(articleToDisplay)"></ArticleComponent>
    <div id="profilePicture">
      <img src="/Clyde.png" />
    </div>
    <div id="researcherInfos">
      <div class="surrounded">{{researcher.user.lastName}} {{researcher.user.firstName}}</div>
      <div class="surrounded">Orcid : {{researcher.orcidId}}</div>
      <div class="surrounded">Email : {{researcher.user.email}}</div>
      <div class="surrounded">
        site : <a :href=researcher.site style="color: #007aff"> {{researcher.site}}</a>
      </div>
      <div class="surrounded">Domain : {{researcher.domain}}</div>
      <div id="coAuthorList" class="surrounded">Co-authors list : <a :href=downloadCoAuthors() download="coAuthors.json"> here </a></div>
    </div>
    <div id="stats">
      <div class="surrounded">
        Stat type :
        <select @change="update()" id="stats-select" v-model="statsOf">
          <option value="views">Views</option>
          <option value="researches">Researches</option>
          <option value="languages">Languages</option>
        </select>
      </div>
      <div class="surrounded">
        Class by:
        <select @change="update()" id="classed-select" v-model="statsBy">
          <option value="years">Years</option>
          <option value="months">Months</option>
          <option value="topics">Topics</option>
        </select>
      </div>
      <div id="statsPie">
		  <CanvasJSChart :options="options" id=chart @chart-ref="c => chart = c "/>
      </div>
    </div>
    <div id="researches">
      <div id="search">
        <input type="text" id="search-input" placeholder="search for researches" v-model="input"/>
        <button id="filterButton" @click="openFilter">  Filters </button>
      </div>
      <ul id="researchUL">
        <li id="researchLi" v-for="n in searchInList(researchList,input)">
          <div class="vl"> {{n.title}}</div>
          <div class="vl"> {{ n.researcher.user.firstName +" "+ n.researcher.user.lastName }}</div>
         <a @click="openResearch(n)"> MoreInfo  </a></li>
      </ul>
    </div>
  </div>
</template>

<style scoped>
#main {
  display: grid;
  grid-template-columns: 22% auto;
  grid-template-rows: 26% auto;
  height: 100%;
  width: 100%;
}

#profilePicture {
  display: flex;
  justify-content: center;
}

#profilePicture img {
  align-self: center;
  justify-self: center;
  width: 60%;
}

#researcherInfos {
  display: grid;
  grid-template-columns: auto auto auto;
  column-gap: 5px;
  grid-template-rows: auto auto;
}

.surrounded {
  border: 2px solid black;
  color: white;
  font-size: x-large;
  align-self: center;
  text-align: center;
  background-color: rgba(255, 255, 255, 0.09);
  border-radius: 20px;
  margin-bottom: 10px;
}

.surrounded select {
  margin-top: 2px;
  margin-bottom: 2px;
  border: 1px solid black;
  color: white;
  background-color: rgb(255, 255, 255, 0.1);
  font-size: large;
}

#statsPie {

}

#search{
  width: 100%;
  height: 10%;
  display: inline-flex;
}
#search-input {
  margin-left: 25px;
  width: 75%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  height: 20px;
  align-self: center;
}

#filterButton {
  align-self: center;
  margin-left: 2px;
  font-size: xx-large;
  color: white;
  background: rgba(191, 64, 191,0.5);
  border:2px solid black;
}
#filterButton:hover{
  background: rgba(191, 64, 191);
}


#researchUL {
  list-style-type: none;
  color: white;
  padding: 12px;
  margin: 5px;
  height: 400px;
  overflow: scroll;
}
#researchLi{
  display: grid;
  grid-template-columns: auto auto auto;
  border: 2px solid black;
  color: white;
  font-size: x-large;
  text-align: center;
  text-indent: 7px;
  background-color: rgba(255, 255, 255, 0.09);
  border-radius: 18px;
  margin-bottom: 15px;
}
a{
  color:#007aff;
  text-decoration: underline;
  cursor: pointer;
}

.vl {
  border-right: 2px solid black;
}

</style>
