<script>
import colors from "@/colors.json";
import * as d3 from "d3";
import * as _ from "lodash";
import * as log from "loglevel";

// type DiagramType = "horizontal" | "vertical" | "horizontalSmall";

export default {
  props: {
    diagramType: {
      type: String,
      default: "horizontal",
    },
    postfix: {
      type: String,
      default: "",
    },
    learningPath: {
      required: true,
      type: Object,
    },
  },
  data() {
    return {
      width: 1640,
      height: 384,
    };
  },
  computed: {
    svgId() {
      return `learningpath-diagram-${this.learningPath.slug}-${this.diagramType}${this.postfix}`;
    },
    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.learningPath) {
        const internalCircles = [];
        this.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.frontend_url = circle.frontend_url;
          newCircle.id = circle.id;
          newCircle.slug = _.kebabCase(circle.title);
          internalCircles.push(newCircle);
        });
        return internalCircles;
      }
      return [];
    },
    svg() {
      const result = d3.select("#" + this.svgId);
      result.selectAll("*").remove();
      return result;
    },
  },

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

    // clean old svg
    d3.select("#" + this.svgId)
      .selectAll("*")
      .remove();

    let circleWidth = 200;
    if (this.diagramType === "vertical") {
      circleWidth = 60;
    }
    const radius = (circleWidth * 0.8) / 2;

    if (this.diagramType === "vertical") {
      this.width = Math.min(960, window.innerWidth - 32);
      this.height = 860;
    } else {
      this.width = circleWidth * this.circles.length;
    }

    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.diagramType === "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(i.frontend_url);
      })

      .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.diagramType === "horizontal") {
          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 + 10;
    }

    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.diagramType === "vertical") {
      const Circles_X = radius;
      const Topics_X = Circles_X - 20;

      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 - circleWidth / 2;
        return "translate(" + x_coord + ", 200)";
      });

      circlesText
        .attr("y", radius + 30)
        .style("text-anchor", "middle")
        .call(wrap, circleWidth - 20)
        .attr("class", () => {
          let classes = "circlesText text-xl font-bold hidden";
          if (this.diagramType === "horizontal") {
            classes += " lg:block";
          }
          return classes;
        });

      topicGroups
        .attr("transform", (d, i) => {
          return (
            "translate(" +
            getTopicHorizontalPosition(i, d, this.learningPath.topics) +
            ",0)"
          );
        })
        .attr("class", (d) => {
          let classes = "topic hidden";
          if (this.diagramType === "horizontal" && d.is_visible) {
            classes += " lg:block";
          }
          return classes;
        });

      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", "topic-title 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="svgId"
      class="learning-path-visualization h-full mx-auto -mt-6 lg:mt-0"
      :class="{
        'max-h-[90px]': ['horizontalSmall'].includes(diagramType),
        'max-h-[90px] lg:max-h-[380px]': ['horizontal'].includes(diagramType),
      }"
      :viewBox="viewBox"
    ></svg>
  </div>
</template>
