<script setup lang="ts">
import * as d3 from "d3";
import {computed, onMounted} from "vue";
import * as _ from 'underscore'
import {useCircleStore} from '@/stores/circle';
import * as log from 'loglevel';

const circleStore = useCircleStore();

function someFinished(learningSequence) {
  if (circleStore.circle) {
    return circleStore.circle.someFinishedInLearningSequence(learningSequence.translation_key);
  }
  return false;
}

onMounted(async () => {
  log.info('CircleDiagram mounted');
  render();
});


const pieData = computed(() => {
  const circle = circleStore.circle
  console.log('initial of compute pie data ', circle)

  if (circle) {
    console.log('initial of compute pie data ', circle)

    let pieWeights = new Array(Math.max(circle.learningSequences.length, 1)).fill(1)
    let pieGenerator = d3.pie()
    let angles = pieGenerator(pieWeights)
    _.forEach(angles, (pie) => {
      const thisLearningSequence = circle.learningSequences[parseInt(pie.index)]
      pie.title = thisLearningSequence.title
      pie.icon = thisLearningSequence.icon
      pie.startAngle = pie.startAngle + Math.PI
      pie.endAngle = pie.endAngle + Math.PI
      pie.arrowStartAngle = pie.endAngle + (pie.startAngle - pie.endAngle) / 2
      pie.arrowEndAngle = pie.startAngle + (pie.startAngle - pie.endAngle) / 2
      pie.translation_key = thisLearningSequence.translation_key
      pie.done = someFinished(thisLearningSequence)
    })
    angles = angles.reverse()
    return angles
  }
  return {}
})


const blue900 = '#00224D',
  blue700 = '#1A5197',
  gray100 = '#EDF2F6',
  gray300 = '#E0E5EC',
  gray500 = '#B1C1CA',
  sky400 = '#72CAFF',
  sky500 = '#41B5FA'

const width = 450
const height = 450
const radius = Math.min(width, height) / 2.4

function render() {
  const arrowStrokeWidth = 2

  const svg = d3.select('.circle-visualization')
    .attr('viewBox', `0 0 ${width} ${height}`)

  // Append markter as definition to the svg
  svg.append("svg:defs").append("svg:marker")
    .attr("id", "triangle")
    .attr("refX", 11)
    .attr("refY", 11)
    .attr("markerWidth", 20)
    .attr("markerHeight", 20)
    .attr("markerUnits", "userSpaceOnUse")
    .attr("orient", "auto")
    .append("path")
    .attr("d", "M -1 0 l 10 0 M 0 -1 l 0 10")
    .attr('transform', 'rotate(-90, 10, 0)')
    .attr('stroke-width', arrowStrokeWidth)
    .attr('stroke', gray500)

  const g = svg.append('g').attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')')


  // Generate the pie diagram wede
  const wedgeGenerator = d3
    .arc()
    .innerRadius(radius / 2.5)
    .padAngle(12 / 360)
    .outerRadius(radius)


  // Generate the arrows
  const arrowRadius = radius * 1.1


  const learningSequences = g.selectAll('.learningSegmentArc').data(pieData.value).enter().append('g')
    .attr('class', 'learningSegmentArc')
    .attr('role', 'button')
    .attr('fill', gray300)


  learningSequences
    .on('mouseover', function (d, i) {
      d3.select(this)
        .transition()
        .duration('200')
        .attr('fill', (d) => {
          return d.done ? sky400 : gray100
        })

    })
    .on('mouseout', function (d, i) {
      d3.select(this)
        .transition()
        .duration('200')
        .attr('fill', (d) => {
          return d.done ? sky500 : gray300
        })
    })
    .on('click', function (d, elm) {
      console.log('clicked on ', d, elm)
      document.getElementById(elm.translation_key)?.scrollIntoView({behavior: 'smooth'})
    })

  learningSequences
    .transition()
    .duration('1')
    .attr('fill', (d) => {
      return d.done ? sky500 : gray300
    })


  learningSequences.append('path').attr('d', wedgeGenerator)


  const learningSequenceText = learningSequences
    .append('text')
    .attr('fill', blue900)
    .style('font-size', 15)
    .text((d) => {
      return d.title
    })
    .attr("transform", function (d) {
      let translate = wedgeGenerator.centroid(d)
      translate = [translate[0], translate[1] + 20]
      return "translate(" + translate + ")";
    })
    .attr('class', 'circlesText text-xl font-bold')
    .style('text-anchor', 'middle')

  const iconWidth = 25

  const learningSequenceIcon = learningSequences.append("svg:image")
    .attr("xlink:href", (d) => {
      return "/static/icons/" + d.icon.replace("it-", "") + ".svg"
    })
    .attr("width", iconWidth)
    .attr("height", iconWidth)
    .attr("transform", function (d) {
      let translate = wedgeGenerator.centroid(d)
      translate = [translate[0] - iconWidth / 2, translate[1] - iconWidth]
      return "translate(" + translate + ")";
    })


  // Create Arrows
  const arrow = d3
    .arc()
    .innerRadius(arrowRadius)
    .outerRadius(arrowRadius + arrowStrokeWidth)
    .padAngle(20 / 360)
    .startAngle(d => {
      return d.arrowStartAngle
    })
    .endAngle(d => {
      return d.arrowEndAngle
    })


  const arrows = g
    .selectAll('.arrow')
    .data(pieData.value)
    .join('g')
    .attr('class', 'arrow')
    .attr('marker-end', 'url(#triangle)')

  // remove last arrow
  d3.selection.prototype.last = function () {
    let last = this.size() - 1;
    return d3.select(this.nodes()[last]);
  };


  const all_arows = g.selectAll('.arrow')
  all_arows.last().remove()

  //Draw arrow paths
  arrows.append('path').attr('fill', gray500).attr('d', arrow)
  return svg
}

</script>


<template>
  <div class="svg-container h-full content-center">
    <pre hidden>{{ pieData }}</pre>
    <pre hidden>{{render()}}</pre>
    <svg class="circle-visualization h-full">
      <circle v-if="!circleStore.circle" :cx="width / 2" :cy="height / 2" :r="radius" :color="gray300"/>
      <circle v-if="!circleStore.circle" :cx="width / 2" :cy="height / 2" :r="radius / 2.5" color="white"/>
    </svg>
  </div>
</template>
