import type {
  CircleType,
  LearningContent,
  LearningContentWithCompletion,
  LearningUnit,
} from "@/types";
import * as log from "loglevel";
import { defineStore } from "pinia";
import type { RouteLocationNormalized } from "vue-router";

export type CircleStoreState = {
  page: "INDEX" | "OVERVIEW";
};

function createLearningUnitHash(
  circle: CircleType,
  learningUnitSlug: string | undefined
) {
  if (learningUnitSlug && circle) {
    return "#" + learningUnitSlug.replace(`${circle.slug}-`, "");
  }

  return "";
}

export const useCircleStore = defineStore({
  id: "circle",
  state: () => {
    return {
      page: "INDEX",
    } as CircleStoreState;
  },
  getters: {},
  actions: {
    openLearningContent(learningContent: LearningContent) {
      this.router.push({
        path: learningContent.frontend_url,
      });
    },
    closeLearningContent(
      learningContent: LearningContentWithCompletion,
      circle: CircleType,
      returnRoute?: RouteLocationNormalized
    ) {
      if (returnRoute) {
        this.router.push(returnRoute);
      } else {
        this.router.push({
          path: `${circle.frontend_url}`,
          hash: createLearningUnitHash(
            circle,
            learningContent.parentLearningUnit?.slug
          ),
        });
      }
    },
    openSelfEvaluation(learningUnit: LearningUnit) {
      this.router.push({
        path: learningUnit.evaluate_url,
      });
    },
    closeSelfEvaluation(
      learningUnit: LearningUnit,
      circle: CircleType,
      returnRoute?: RouteLocationNormalized
    ) {
      if (returnRoute) {
        this.router.push(returnRoute);
      } else {
        this.router.push({
          path: `${circle.frontend_url}`,
          hash: createLearningUnitHash(circle, learningUnit.slug),
        });
      }
    },
    async continueFromLearningContent(
      currentLearningContent: LearningContentWithCompletion,
      circle: CircleType,
      returnRoute?: RouteLocationNormalized,
      markCompletionFn?: (
        learningContent: LearningContentWithCompletion
      ) => Promise<void>
    ) {
      if (currentLearningContent) {
        if (currentLearningContent.can_user_self_toggle_course_completion) {
          if (markCompletionFn) {
            await markCompletionFn(currentLearningContent);
          }
        }
        this.closeLearningContent(currentLearningContent, circle, returnRoute);
      } else {
        log.error("currentLearningContent is undefined");
      }
    },
    continueFromSelfEvaluation(learningUnit: LearningUnit, circle: CircleType) {
      this.closeSelfEvaluation(learningUnit, circle);
    },
  },
});
