import("./utils.js").then((utils) => {
  import(/* @vite-ignore */utils.coreVersion()).then((core) => {
    //core.store.subscribeVirtualContainerTo('https://api.tzcld-dev.startinblox.com/communities/', 'https://api.tzcld-dev.startinblox.com/tzcld-communities-evaluation-point-answers/');
    core.Sib.register({
        name: "autoeval-graph",
        use: [core.StoreMixin],
  
        empty() {
          //console.debug();
          this.element.innerHTML = "";
        },
  
        async populate() {
          this.element.innerHTML = `
          <div class="segment full shadow bg-color-white padding-large margin-bottom-large">
          <div class="loader">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
          </div></div>`;
          let communityTzcldprofile = {
            profile: await this.resource,

          };
          let tzcldprofile = {
            community: await communityTzcldprofile.profile.community,

          };
          let ResourceAnswers = (await tzcldprofile.community.community_answer) ;
          let answers = ResourceAnswers["ldp:contains"] ;
          let community_id = utils.getIntId(tzcldprofile.community['@id']) ;
          if("label" in this.element.attributes) {
            for(let ignore of this.element.attributes['label'].value.split(',')) {
              tzcldprofile[ignore.trim()] = null;
            }
          }

          let points = [] ;
          for(let answer of answers) {
            let pointResource = await answer.evaluation_point;
            let pointPartResource = await pointResource.part;
            let pointPartId = utils.getIntId(await pointPartResource['@id']) ;
            let pointPartOrder = await pointPartResource.order ;
            let pointPartLabel = await pointPartResource.title ;
            let prevLabel = null ;

            core.store.subscribeVirtualContainerTo(communityTzcldprofile.profile['@id'], await answer['@id']);
            if (await answer.answer == true) {
              if (typeof points[pointPartId] != "undefined") {
                points[pointPartId].data++ ;
              } else {
                points[pointPartId]= {
                  label: pointPartLabel,
                  data: 1,
                  order: pointPartOrder
                } ;
              }
                
            } else {
              if (typeof points[pointPartId] == "undefined") {
                points[pointPartId]= {
                  label: pointPartLabel,
                  data: 0,
                  order: pointPartOrder
                } ;
              }
            }
          }
          points = points.sort(function(a,b){
              return a.order - b.order;
            })
          // fix null label
          let finalPoints = [] ;
          let lastNotEmty = 0 ;
          let labelData = [] 
          for (let p in points) {
            if (points[p].label == null) {
              finalPoints[lastNotEmty].data = finalPoints[lastNotEmty].data + points[p].data ;
            } else {
              lastNotEmty = p ;
              finalPoints[p] = points[p] ;
            }
          }

          let labelsData = [] ;
          let datasData = [] ;
          for (let p in finalPoints) {
              labelsData.push(finalPoints[p].label) ;
              datasData.push(finalPoints[p].data) ;
          }
          let graphData = {
            labels: labelsData,
            datasets: [{
              label: '',
              data: datasData,
              fill: true,
              backgroundColor: 'rgba(54, 162, 235, 0.2)',
              borderColor: 'rgb(54, 162, 235)',
              pointBackgroundColor: 'rgb(54, 162, 235)',
              pointBorderColor: '#fff',
              pointHoverBackgroundColor: '#fff',
              pointHoverBorderColor: 'rgb(54, 162, 235)'
            }]
          };
          let graphData2 = {
            labels: labelsData,
            datasets: [{
              axis: 'y',
              data: datasData,
              fill: false,
              backgroundColor: 'rgba(54, 162, 235, 0.2)',
              borderColor: 'rgb(54, 162, 235)',
              pointBackgroundColor: 'rgb(54, 162, 235)',
              pointBorderColor: '#fff',
              pointHoverBackgroundColor: '#fff',
              pointHoverBorderColor: 'rgb(54, 162, 235)'
            }]
          };
           
          let render = `
          <div class="segment block md-whitespace-normal sm-whitespace-normal">
            <div class="segment half md-full sm-full padding-right-small md-padding-none sm-padding-none text-top margin-bottom-large">
              <div class="segment full shadow bg-color-white">
                <div style="width: 90%; display: block;margin: 20px auto;">
                  <canvas id="auto-eval-graphe-1_${community_id}" width="300" height="300"></canvas>
                </div>
              </div>
            </div>
            <div class="segment half md-full sm-full padding-left-small md-padding-none sm-padding-none text-top margin-bottom-large">
              <div class="segment full shadow bg-color-white">

                <solid-display
                        solid-resource=""  
                        data-src="${await tzcldprofile.community['@id']}"
                        fields="segment1(information)"
                        nested-field="tzcld_profile"
                        class-segment1="segment full text-top whitespace-normal padding-large" 
                        widget-information="solid-display-value-markdown" 
                ></solid-display>
              </div>
            </div>
          </div>
          `;
          this.element.innerHTML = render;
          loadgrph(community_id, graphData, graphData2) ;
          
        }
    });

    function loadgrph(community_id, graphData, graphData2) {
      const data = graphData;
      const data2 = graphData2;
      new Chart(
        document.getElementById('auto-eval-graphe-1_'+community_id),
        {
          type: 'radar',
          data: data,
          options: {
            responsive: true,
            maintainAspectRatio: false,
            onResize(chart, x) {
              chart.update() ;
            },
            elements: {
              line: {
                borderWidth: 2
              }
            },
            scales: {
              r: {
                  angleLines: {
                      display: true,
                      color: '#1A2C5F'
                  },
                  suggestedMin: 0,
                  suggestedMax: 5,
                  ticks: {
                      stepSize: 1,
                      color: '#1A2C5F',
                  }, 
                  grid: {
                    color: '#1A2C5F'
                  },
                  pointLabels: {
                    color: '#1A2C5F',
                    font: {
                        size: 14
                    },
                    callback: function(value) {
                      if (typeof value === 'string' && value.length > 25) {
                        return value.substring(0, 25)+'...'; // cutting
                      } 
                      return value ;         
                    }
                  }
              }
            },
            plugins: {
              legend: {
                display: false
              },
            }
          },
        }
      );
      /*new Chart(
        document.getElementById('auto-eval-graphe-2_'+community_id),
        {
          type: 'bar',
          data: data2,
          options: {
            responsive: true,
            indexAxis: 'y',
            maintainAspectRatio: false,
            onResize(chart, x) {
              chart.update() ;
            },
            elements: {
              line: {
                borderWidth: 2
              }
            },
            scales: {
              x: {
                title: {
                  color: '#1A2C5F'
                },
                min: 0,
                max: 5,
                ticks: {
                    stepSize: 1,
                    color: '#1A2C5F'
                }, 
                grid: {
                  color: 'transparent'
                },
                pointLabels: {
                  color: '#1A2C5F',
                  font: {
                      size: 14
                  }
                }
              },
              y: { 
                pointLabels: {
                  color: '#1A2C5F',
                  font: {
                      size: 14
                  }
                }, 
                grid: {
                  color: 'transparent'
                },
                ticks: {
                    color: '#1A2C5F',
                    callback: function(value) {
                      let label = this.getLabelForValue(value) ;
                      if (typeof label === 'string' && label.length > 25) {
                        return label.substring(0, 25)+'...'; // cutting
                      } 
                      return label ;         
                    }
                },
              }
            },
            plugins: {
              legend: {
                display: false
              }
            }
          },
        }
      );*/
    }

    function splitLabelForChart(label) {
      if (Array.isArray(label)) {
        return label ; 
      }
      const words = label.split(' ');
      const lineLimit = 14;
      const lines = [];
    
      let line = '';
      let currentWordIdx = 0;
    
      while (currentWordIdx < words.length) {
        if (line.length + words[currentWordIdx].length < lineLimit) {
          line += `${words[currentWordIdx]} `;
          currentWordIdx++;
    
          if (currentWordIdx === words.length) {
            lines.push(line);
          }
        } else {
          if (line.length) {
            lines.push(line);
            line = '';
          }
    
          if (words[currentWordIdx].length >= lineLimit) {
            lines.push([words.currentWord]);
            currentWordIdx++;
          }
        }
      }
      return lines;
    }
  });
});