<script>
 import { tick } from 'svelte';
 import { goto } from '$app/navigation';

 import {
     Container,
     Icon,
 } from '@sveltestrap/sveltestrap';

 import WordCloud from 'wordcloud';

 import { themesStore } from '$lib/stores/themes.js';

 // Override theme color
 document.body.style.backgroundColor = "";

 tick().then(() => {
     WordCloud(
         document.getElementById('wordcloud'),
         {
             list: computeTags(),
             gridSize: Math.round(20 * document.getElementById('wordcloud').clientWidth / 1024),
             weightFactor: function (size) {
                 return Math.pow(size, 2.8) * document.getElementById('wordcloud').clientWidth / 1024;
             },
             rotateRatio: 0.5,
             ellipticity: 14,
             click: (item) => {
                 goto('tags/' + item[0]);
             },
         }
     );
 });

 function computeTags() {
     const ttags = { };

     for (const key in $themesStore) {
         const theme = $themesStore[key];
         for (const k in theme.exercices) {
             const exercice = theme.exercices[k];
             for (const tag of exercice.tags) {
                 if (!ttags[tag]) ttags[tag] = 1;
                 else ttags[tag] += 1;
             }
         }
     }

     const tags = [];
     for (const tag in ttags) {
         tags.push([tag, ttags[tag]]);
     }

     return tags;
 }
</script>

<Container class="mt-2 d-flex">
    <canvas id="wordcloud" class="w-100" width="1600" height="730"></canvas>
</Container>
