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


const props = defineProps<{
  circleStore: {},
  width: {
    default: 500,
    type: number,
    required: false

  },
  height: {
    default: 500,
    type: number,
    required: false
  },
}>()


function someFinished(learningSequence) {
    return props.circleStore.flatChildren.filter((lc) => {
      return lc.completed && lc.parentLearningSequence?.translation_key === learningSequence.translation_key;
    }).length > 0;
}


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

  if (circle && completionData) {
    console.log('initial of compute pie data ', circle, completionData)
    let learningSequences = _.filter(circle.children, (child) => {
      return child.type === 'learnpath.LearningSequence';
    })

    const completionDataByPageId = _.object(_.map(completionData, function (item) {
      console.log(item)
      return [item.page_key, item]
    }))

    let pieWeights = new Array(Math.max(learningSequences.length, 1)).fill(1)
    let pieGenerator = d3.pie()
    let angles = pieGenerator(pieWeights)
    _.forEach(angles, (pie) => {
      const thisLearningSequence = 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
      console.log(someFinished(thisLearningSequence))
      pie.done = someFinished(thisLearningSequence)
    })
    angles = angles.reverse()
    return angles
  }
  return {}
})

onMounted(async () => {
     const width = 450, //props.width,
      height = 450, //props.height,
      radius: number = Math.min(width, height) / 2.4,
      arrowStrokeWidth = 2

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


    const svg = d3.select('.circle-visualization')
      .attr('width', width)
      .attr('height', height)

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

    // 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)


    // 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
          })
      })

    learningSequences
      .transition()
      .duration('1000')
      .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)
      .enter()
      .append('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)


  }
);


function viewBox() {
  return `0 0 ${width} ${height}`
}


</script>


<template>
  <div class="svg-container h-full content-center">
    <svg class="circle-visualization h-full" :viewBox="viewBox">
    </svg>
  </div>
</template>
