<script>
import * as d3 from 'd3';
import {useLearningPathStore} from '../../stores/learningPath';

export default {
  props: {
    learningPathContents: {
      default: {
        topics: [
          {
            id: 4,
            title: 'Basissdf',
            slug: 'basissdf',
            type: 'learnpath.Topic',
            translation_key: 'fdabcf72-728a-4279-ba34-e079761a14ad',
            is_visible: false,
            circles: [
              {
                id: 5,
                title: 'Basis',
                slug: 'basis',
                type: 'learnpath.Circle',
                translation_key: '13951cfd-b36d-42d5-b84a-178f0a7da106',
                learning_sequences: [
                  {
                    id: 11,
                    title: 'Starten',
                    done: false,
                  },
                  {
                    id: 13,
                    title: 'Beobachten',
                    done: false,
                  },
                ],
              },
            ],
          },

        ],
      },
      type: Object,
    },

    width: {
      default: 1640,
      type: Number,
    },
    height: {
      default: 256 * 3,
      type: Number,
    },
    vertical: {
      default: false,
      type: Boolean
    }
  },
  setup() {
    const learningPathStore = useLearningPathStore()

    return {learningPathStore}
  },
  computed: {
    viewBox() {
      return `0 0 ${this.width} ${this.height * 1.5}`
    },
    circles() {
      if (this.learningPathStore.learningPath) {
        let internalCircles = this.learningPathStore.learningPath.circles;
        internalCircles.forEach((circle) => {
          let pieWeights = new Array(Math.max(circle.learningSequences.length, 1)).fill(1)
          let pieGenerator = d3.pie()
          let pieData = pieGenerator(pieWeights)
          pieData.forEach((pie) => {
            pie.startAngle = pie.startAngle + Math.PI
            pie.endAngle = pie.endAngle + Math.PI
            const lp = circle.learningSequences[parseInt(pie.index)];
            pie.done = circle.someFinishedInLearningSequence(lp.translation_key);
          });
          circle.pieData = pieData.reverse()


        });
        return internalCircles
      }
      return [];
    },
    svg() {
      return d3.select('.learning-path-visualization')

    },

  },

  mounted() {
    const circleWidth = this.vertical ? 100 : 200
    const radius = (circleWidth * 0.8) / 2
    const blue900 = '#00224D',
      blue700 = '#1A5197',
      gray100 = '#EDF2F6',
      gray300 = '#E0E5EC',
      gray500 = '#B1C1CA',
      sky400 = '#72CAFF',
      sky500 = '#41B5FA'

    let vueRouter = this.$router

    // Create append pie charts to the main svg
    const circle_groups = this.svg
      .selectAll('.circle')
      .data(this.circles)
      .enter()
      .append('g')
      .attr('class', 'circle')
      .on('mouseover', function (d, i) {
        d3.select(this)
          .selectAll('.learningSegmentArc')
          .transition()
          .duration(200)
          .attr('fill', (d) => {
            return d.done ? sky400 : gray100
          })
      })
      .on('mouseout', function (d, i) {
        d3.select(this)
          .selectAll('.learningSegmentArc')
          .transition()
          .duration(200)
          .attr('fill', (d) => {
            return d.done ? sky500 : gray300
          })
      })
      .on('click', function (d, i) {
        vueRouter.push('/circle/' + i.slug)
      })

      .attr('role', 'button')

    const arcGenerator = d3
      .arc()
      .innerRadius(radius / 2)
      .padAngle(12 / 360)
      .outerRadius(radius)

    //Generate groups
    const arcs = this.svg
      .selectAll('g')
      .selectAll('.learningSegmentArc')
      .data((d) => {
        return d.pieData
      })
      .enter()
      .append('g')
      .attr('class', 'learningSegmentArc')
      .attr('fill', gray300)

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

    //Draw arc paths
    arcs.append('path').attr('d', arcGenerator)


    const circlesText = circle_groups
      .append('text')
      .attr('fill', blue900)
      .style('font-size', 19)
      .text((d) => d.title)
      .attr('class', 'circlesText text-xl font-bold hidden lg:block')

    const topicHeightOffset = 20
    const topicHeight = 35
    const circleHeigth = circleWidth + 20

    function getTopicPosition(i, d, topics) {
      let pos = topicHeightOffset

      for (let index = 0; index < i; index++) {
        let topic = topics[index]
        if (topic.is_visible) {
          pos += topicHeight
        }
        pos += circleHeigth * topic.circles.length
      }
      return pos + topicHeightOffset
    }

    function getCircleVerticalPostion(i, d, topics) {
      let y = circleHeigth / 2 + topicHeightOffset + 10
      for (let topic_index = 0; topic_index < topics.length; topic_index++) {
        const topic = topics[topic_index]
        console.log(topic.title)
        if (topic.is_visible) {
          y += topicHeight

        }
        for (let circle_index = 0; circle_index < topic.circles.length; circle_index++) {
          let circle = topic.circles[circle_index]
          console.log('-  ' + circle.title)
          if (circle.id === d.id) {
            console.log('found')
            return y
          }
          y += circleHeigth

        }
      }
    }


    const topicGroups = this.svg
      .selectAll('.topic')
      .data(this.learningPathStore.learningPath.topics)
      .enter()
      .append('g')
      .attr('class', (d) => {
        return 'topic '.concat(d.is_visible ? "hidden lg:block" : "hidden")
      })

    const topicLines = topicGroups
      .append('line')
      .attr('class', 'stroke-gray-500')
      .attr('stroke-width', 1.76)

    const ç = topicGroups
      .append('text')
      .attr('fill', blue900)
      .style('font-size', 19)
      .text((d) => d.title)


    // Calculate positions of objects

    if (this.vertical) {
      circle_groups
        .attr('transform', (d, i) => {
          return 'translate(100,' + getCircleVerticalPostion(i, d, this.learningPathStore.learningPath.topics) + ')'
        })

      circlesText
        .attr('y', 7)
        .attr('x', radius + 40)

      const Topics_X = 100 - radius

      topicGroups.attr('transform', (d, i) => {
        return "translate(" + Topics_X + ", " + getTopicPosition(i, d, this.learningPathStore.learningPath.topics) + ")"
      })
        .attr('class', 'topicTitles')


      topicLines.attr('x1', 0)
        .attr('y1', -20)
        .attr('x2', 0)
        .attr('y2', -20)
        .transition().duration('1000').attr('x2', this.width * 0.8)


    } else {
      circle_groups.attr('transform', (d, i) => {
        let x_coord = (i + 1) * circleWidth - radius
        return 'translate(' + x_coord + ', 200)'
      })

      circlesText.attr('y', radius + 30)
        .style('text-anchor', 'middle')
        .call(wrap, circleWidth - 20)

      topicGroups.attr('transform', (d, i) => {
        return "translate(" + getTopicPosition(i, d, this.learningPathStore.learningPath.topics) + ",0)"
      })

      topicLines.attr('x1', -10)
        .attr('y1', 0)
        .attr('x2', -10)
        .attr('y2', 0)
        .transition().duration('1000').attr('y2', 350)

      topicGroups.attr('y', 20)
        .call(wrap, circleWidth)
        .attr('class', 'topicTitles font-bold')


    }


    function flipToVertical() {

      this.height = 2000

      const animationTime = 1000
      circle_groups
        .transition().duration(animationTime).attr('transform', (d, i) => {
        let y_coord = ((i + 1) * circleWidth - radius) * 0.5
        return 'translate(200, ' + y_coord + ') scale(0.5)'
      }).on("end", d => {
        addTexts()
      })
      circle_groups.selectAll('.circlesText').attr('class', 'hidden')
      topicGroups.attr('class', 'hidden')


      function addTexts() {


        circle_groups
          .append('text')
          .attr('fill', blue900)
          .style('font-size', 45)
          .text((d) => d.title)
          .attr('y', 0)
          .attr('x', radius + 30)
          .attr('class', 'circlesText text-xl font-bold')
          .style('text-anchor', 'left')
      }


    }

    function wrap(text, width) {
      text.each(function () {
        let text = d3.select(this),
          words = text.text().split(/\s+/).reverse(),
          word,
          line = [],
          lineNumber = 0,
          lineHeight = 1.1, // ems
          y = text.attr('y'),
          dy = 0, //parseFloat(text.attr('dy')),
          tspan = text
            .text(null)
            .append('tspan')
            .attr('x', 0)
            .attr('y', y)
            .attr('dy', dy + 'em')
        while ((word = words.pop())) {
          line.push(word)
          tspan.text(line.join(' '))
          if (tspan.node().getComputedTextLength() > width) {
            line.pop()
            tspan.text(line.join(' '))
            line = [word]

            tspan = text
              .append('tspan')
              .attr('x', 0)
              .attr('y', y)
              .attr('dy', ++lineNumber * lineHeight + dy + 'em')
              .text(word)
          }
        }
      })
    }
  },
}
</script>


<template>
  <div class="flex flex-col">
    <button class="content-center">
      <it-icon-list/>
      Listen ansicht anzeigen
    </button>
    <div class="svg-container h-full content-start">
      <svg class="learning-path-visualization h-full" :viewBox="viewBox">
      </svg>
    </div>
  </div>

</template>

