<script>
import colors from "@/colors.json";
import { useLearningPathStore } from "@/stores/learningPath";
import * as d3 from "d3";
import * as log from "loglevel";

export default {
  props: {
    vertical: {
      default: false,
      type: Boolean,
    },
    identifier: {
      required: true,
      type: String,
    },
  },
  setup() {
    const learningPathStore = useLearningPathStore();
    return { learningPathStore };
  },
  data() {
    return {
      width: 1640,
      height: 384,
    };
  },
  computed: {
    viewBox() {
      return `0 0 ${this.width} ${this.height}`;
    },
    circles() {
      function someFinished(circle, learningSequence) {
        if (circle) {
          return circle.someFinishedInLearningSequence(
            learningSequence.translation_key
          );
        }
        return false;
      }

      function allFinished(circle, learningSequence) {
        if (circle) {
          return circle.allFinishedInLearningSequence(learningSequence.translation_key);
        }
        return false;
      }

      if (this.learningPathStore.learningPath) {
        const internalCircles = [];
        this.learningPathStore.learningPath.circles.forEach((circle) => {
          const pieWeights = new Array(
            Math.max(circle.learningSequences.length, 1)
          ).fill(1);
          const pieGenerator = d3.pie();
          const pieData = pieGenerator(pieWeights);
          pieData.forEach((pie) => {
            const thisLearningSequence = circle.learningSequences[parseInt(pie.index)];
            pie.startAngle = pie.startAngle + Math.PI;
            pie.endAngle = pie.endAngle + Math.PI;
            pie.done = circle.someFinishedInLearningSequence(
              thisLearningSequence.translation_key
            );
            pie.someFinished = someFinished(circle, thisLearningSequence);
            pie.allFinished = allFinished(circle, thisLearningSequence);
          });
          const newCircle = {};
          newCircle.pieData = pieData.reverse();
          newCircle.title = circle.title;
          newCircle.slug = circle.slug.replace(
            `${circle.parentLearningPath.slug}-circle-`,
            ""
          );
          newCircle.id = circle.id;
          internalCircles.push(newCircle);
        });
        return internalCircles;
      }
      return [];
    },
    svg() {
      return d3.select("#" + this.identifier);
    },

    learningPath() {
      return Object.assign({}, this.learningPathStore.learningPath);
    },
  },

  mounted() {
    log.debug("LearningPathDiagram mounted");

    if (this.vertical) {
      this.width = Math.min(960, window.innerWidth - 32);
      this.height = 860;
    }

    const circleWidth = this.vertical ? 60 : 200;
    const radius = (circleWidth * 0.8) / 2;

    function getColor(d) {
      let color = colors.gray[300];
      if (d.someFinished) {
        color = colors.sky[500];
      }
      if (d.allFinished) {
        color = colors.green[500];
      }
      return color;
    }

    function getHoverColor(d) {
      let color = colors.gray[200];
      if (d.someFinished) {
        color = colors.sky[400];
      }
      if (d.allFinished) {
        color = colors.green[400];
      }
      return color;
    }

    const 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")
      .attr("data-cy", (d) => {
        if (this.vertical) {
          return `circle-${d.slug}-vertical`;
        } else {
          return `circle-${d.slug}`;
        }
      })
      .on("mouseover", function (d, i) {
        d3.select(this)
          .selectAll(".learningSegmentArc")
          .transition()
          .duration(200)
          .attr("fill", (d) => {
            return getHoverColor(d);
          });
      })
      .on("mouseout", function (d, i) {
        d3.select(this)
          .selectAll(".learningSegmentArc")
          .transition()
          .duration(200)
          .attr("fill", (d) => {
            return getColor(d);
          });
      })
      .on("click", (d, i) => {
        vueRouter.push(`/learn/${this.learningPathStore.learningPath.slug}/${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", colors.gray[300]);

    arcs
      .transition()
      .duration(1000)
      .attr("fill", (d) => {
        return getColor(d);
      });

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

    const circlesText = circle_groups
      .append("text")
      .attr("fill", colors.blue[900])
      .style("font-size", "18px")
      .style("overflow-wrap", "break-word")
      .text((d) => {
        if (!this.vertical) {
          return d.title.replace("Prüfungsvorbereitung", "Prüfungs- vorbereitung");
        }
        return d.title;
      });

    const topicHeightOffset = 20;
    const topicHeight = 50;
    const circleHeigth = circleWidth + 20;

    function getTopicHorizontalPosition(i, d, topics) {
      let x = 0;
      for (let index = 0; index < i; index++) {
        x += circleWidth * topics[index].circles.length;
      }
      return x + 30;
    }

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

      for (let index = 0; index < i; index++) {
        const 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];
        if (topic.is_visible) {
          y += topicHeight;
        }
        for (
          let circle_index = 0;
          circle_index < topic.circles.length;
          circle_index++
        ) {
          const circle = topic.circles[circle_index];
          if (circle.id === d.id) {
            return y;
          }
          y += circleHeigth;
        }
      }
    }

    const topicGroups = this.svg
      .selectAll(".topic")
      .data(this.learningPath.topics)
      .enter()
      .append("g");

    const topicLines = topicGroups
      .append("line")
      .attr("class", "stroke-gray-500")
      .attr("stroke-width", 1);

    const topicTitles = topicGroups
      .append("text")
      .attr("fill", colors.blue[900])
      .style("font-size", "16px")
      .text((d) => d.title);

    // Calculate positions of objects

    if (this.vertical) {
      const Circles_X = radius;
      const Topics_X = Circles_X - radius;

      circle_groups.attr("transform", (d, i) => {
        return (
          "translate(" +
          Circles_X +
          "," +
          getCircleVerticalPostion(i, d, this.learningPath.topics) +
          ")"
        );
      });

      circlesText
        .attr("y", 7)
        .attr("x", radius + 40)
        .attr("class", "circlesText text-xl font-bold block");

      topicGroups
        .attr("transform", (d, i) => {
          return (
            "translate(" +
            Topics_X +
            ", " +
            getTopicVerticalPosition(i, d, this.learningPath.topics) +
            ")"
          );
        })
        .attr("class", (d) => {
          return "topic ".concat(d.is_visible ? "block" : "hidden");
        });

      topicLines.transition().duration("1000").attr("x2", this.width);

      topicTitles.attr("y", 30);
    } else {
      circle_groups.attr("transform", (d, i) => {
        const x_coord = (i + 1) * circleWidth - radius;
        return "translate(" + x_coord + ", 200)";
      });

      circlesText
        .attr("y", radius + 30)
        .style("text-anchor", "middle")
        .call(wrap, circleWidth - 20)
        .attr("class", "circlesText text-xl font-bold hidden lg:block");

      topicGroups
        .attr("transform", (d, i) => {
          return (
            "translate(" +
            getTopicHorizontalPosition(
              i,
              d,
              this.learningPathStore.learningPath.topics
            ) +
            ",0)"
          );
        })
        .attr("class", (d) => {
          return "topic ".concat(d.is_visible ? "hidden lg:block" : "hidden");
        });

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

      topicTitles
        .attr("y", 20)
        .style("font-size", "18px")
        .call(wrap, circleWidth * 0.8)
        .attr("class", "topicTitles font-bold");
    }

    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="svg-container h-full content-start">
    <svg
      :id="identifier"
      class="learning-path-visualization h-full"
      :viewBox="viewBox"
    ></svg>
  </div>
</template>
