<script setup lang="ts">
import * as d3 from "d3";
import * as _ from "lodash";
import * as log from "loglevel";

// @ts-ignore
import colors from "@/colors.json";

import type { Circle } from "@/services/circle";
import type { LearningPath } from "@/services/learningPath";
import type { LearningSequence, Topic } from "@/types";
import { computed, onMounted, reactive, watch } from "vue";
import { useRouter } from "vue-router";

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

export interface Props {
  diagramType?: DiagramType;
  postfix?: string;
  profileUserId?: string;
  learningPath: LearningPath;
  // set to undefined (default) to show all circles
  showCircleTranslationKeys: string[];
}

const props = withDefaults(defineProps<Props>(), {
  diagramType: "horizontal",
  postfix: "",
  profileUserId: "",
  showCircleTranslationKeys: undefined,
});

log.debug(
  "LearningPathDiagram created",
  props.postfix,
  props.profileUserId,
  props.showCircleTranslationKeys
);

const state = reactive({ width: 1640, height: 384 });

const svgId = computed(() => {
  return `learningpath-diagram-${props.learningPath?.slug}-${props.diagramType}${props.postfix}`;
});

const viewBox = computed(() => {
  return `0 0 ${state.width} ${state.height}`;
});

const vueRouter = useRouter();

onMounted(async () => {
  log.debug("LearningPathDiagram mounted", props.postfix, props.profileUserId);
  render();
});

watch(
  () => props.showCircleTranslationKeys,
  (newCircleIds, oldCircleIds) => {
    log.debug("LearningPathDiagram showCircleIds changed", newCircleIds, oldCircleIds);
    render();
  },
  { deep: true }
);

function someFinished(circle: Circle, learningSequence: LearningSequence) {
  if (circle) {
    return circle.someFinishedInLearningSequence(learningSequence.translation_key);
  }
  return false;
}

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

function circleUrl(circle: InternalCircle) {
  let circleUrl = circle.frontend_url;
  if (props.profileUserId) {
    circleUrl = `/course/${props.learningPath.course.slug}/cockpit/profile/${props.profileUserId}/${circle.slug}`;
  }
  return circleUrl;
}

interface CirclePie extends d3.PieArcDatum<number> {
  someFinished: boolean;
  allFinished: boolean;
  done: boolean;
}

interface InternalCircle {
  id: number;
  translation_key: string;
  title: string;
  frontend_url: string;
  slug: string;
  pieData: CirclePie[];
}

function isCircleVisible(circleTranslationKey: string) {
  if (props.showCircleTranslationKeys) {
    return props.showCircleTranslationKeys.includes(circleTranslationKey);
  }

  return true;
}

const circles = computed(() => {
  if (props.learningPath) {
    const internalCircles: InternalCircle[] = [];
    props.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 as CirclePie[]).forEach((pie) => {
        const thisLearningSequence = circle.learningSequences[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);
      });

      if (isCircleVisible(circle.translation_key)) {
        internalCircles.push({
          pieData: pieData.reverse() as CirclePie[],
          title: circle.title,
          frontend_url: circle.frontend_url,
          id: circle.id,
          translation_key: circle.translation_key,
          slug: _.kebabCase(circle.title),
        });
      }
    });
    return internalCircles;
  }
  return [];
});

function render() {
  log.debug("LearningPathDiagram render");
  // clean old svg
  d3.select("#" + svgId.value)
    .selectAll("*")
    .remove();

  const svgElement = d3.select("#" + svgId.value);
  // Clean svg before adding new stuff.
  svgElement.selectAll("*").remove();

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

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

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

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

  // Create append pie charts to the main svg
  const circle_groups = svgElement
    .selectAll(".circle")
    .data(circles.value)
    .enter()
    .append("g")
    .attr("class", (internalCircle) => {
      let result = "circle";
      if (!isCircleVisible(internalCircle.translation_key)) {
        result += " hidden";
      }
      return result;
    })
    .attr("data-cy", (d) => {
      if (props.diagramType === "vertical") {
        return `circle-${d.slug}-vertical`;
      } else {
        return `circle-${d.slug}`;
      }
    })
    .on("mouseover", function () {
      d3.select(this)
        .selectAll(".learningSegmentArc")
        .transition()
        .duration(200)
        .attr("fill", (d) => {
          return getHoverColor(d as CirclePie);
        });
    })
    .on("mouseout", function () {
      d3.select(this)
        .selectAll(".learningSegmentArc")
        .transition()
        .duration(200)
        .attr("fill", (d) => {
          return getColor(d as CirclePie);
        });
    })
    .on("click", (d, i) => {
      vueRouter.push(circleUrl(i));
    })

    .attr("role", "button");

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

  //Generate groups
  const arcs = svgElement
    .selectAll("g")
    .selectAll(".learningSegmentArc")
    .data((d) => {
      return (d as InternalCircle).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
  // @ts-ignore
  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 (props.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: number, _d: unknown, topics: Topic[]) {
    let x = 0;
    for (let index = 0; index < i; index++) {
      x += circleWidth * topics[index].circles.length;
    }
    return x + 10;
  }

  function getTopicVerticalPosition(i: number, _d: unknown, topics: Topic[]) {
    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: number, d: InternalCircle, topics: Topic[]) {
    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 = svgElement
    .selectAll(".topic")
    .data(props.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 (props.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, props.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, props.learningPath.topics) +
          ")"
        );
      })
      .attr("class", (d) => {
        return "topic ".concat(d.is_visible ? "block" : "hidden");
      });

    topicLines.transition().duration(1000).attr("x2", state.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 (props.diagramType === "horizontal") {
          classes += " lg:block";
        }
        return classes;
      });

    topicGroups
      .attr("transform", (d, i) => {
        return (
          "translate(" +
          getTopicHorizontalPosition(i, d, props.learningPath.topics) +
          ",0)"
        );
      })
      .attr("class", (d) => {
        let classes = "topic hidden";
        if (props.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");
  }

  // @ts-ignore
  function wrap(texts, width: number) {
    texts.each(function () {
      // @ts-ignore
      let text = d3.select(this),
        words = text.text().split(/\s+/).reverse(),
        word,
        lines: string[] = [],
        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())) {
        lines.push(word);
        tspan.text(lines.join(" "));
        // @ts-ignore
        if (tspan.node().getComputedTextLength() > width) {
          lines.pop();
          tspan.text(lines.join(" "));
          lines = [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>
