<template>
  <BaseModal :show="stateStore.showingSettings" @close="close">
    <h1 class="text-3xl font-bold leading-6 text-gray-900 dark:text-white">
      Einstellungen
    </h1>

    <h2 class="mt-5 text-lg font-bold">Klassen PDF Version</h2>

    <div>
      <select ref="classVersionSelect" v-model="selectedClassVersion">
        <option
          v-for="ver in semesterVersions"
          :key="ver.key.join('/')"
          :value="ver.key"
          :disabled="ver.disabled"
        >
          {{ ver.title }}
        </option>
      </select>
    </div>

    <h2 class="mt-5 text-lg font-bold">Studenthub</h2>

    <div>
      <ul class="text-gray-600 dark:text-gray-400 list-decimal ml-5 md:ml-0">
        <li>
          Um die Studenthub-Daten zu verwenden, musst du dich zuerst einloggen
          <span class="italic"
            >(auch wenn der Modulteppich für dich noch nicht funktioniert)</span
          >:
          <span
            class="external-link"
            @click="openURLInNewWindow('https://studenthub.technik.fhnw.ch/')"
            >Login
            <font-awesome-icon icon="fa-solid fa-arrow-up-right-from-square"
          /></span>
        </li>
        <li>
          Danach kann die Ausgabe der APIs jeweils in das textfeld darunter
          kopiert werden.
        </li>
      </ul>

      <div
        class="block my-2"
        :class="[studenthubStore.hasSomeStudenthubData ? '' : 'text-gray-200']"
      >
        <span class="font-bold">Bereits bestandene Module ausblenden: </span>
        <input
          v-model="hideCompletedClasses"
          type="checkbox"
          class="inline w-auto ml-2"
          :disabled="!studenthubStore.hasSomeStudenthubData"
        />
      </div>

      <div class="mb-1">
        <span class="font-bold mr-2">Student JSON:</span>
        <span
          class="external-link"
          @click="
            openURLInNewWindow(
              'https://studenthub.technik.fhnw.ch/api/studenthub/student',
            )
          "
          >API öffnen
          <font-awesome-icon icon="fa-solid fa-arrow-up-right-from-square"
        /></span>
      </div>
      <textarea
        :onchange="studenthubStudentChanged"
        :class="[
          errors.studenthubStudentParseError ? 'border border-red-500' : '',
        ]"
        class="font-mono w-full h-32 dark:bg-gray-900 bg-gray-100 p-1 text-xs"
        :value="
          studenthubStore.student ? JSON.stringify(studenthubStore.student) : ''
        "
      />
    </div>

    <div class="mt-2">
      <div class="mb-1">
        <span class="font-bold mr-2">Anmeldungen JSON:</span>
        <span
          class="external-link"
          @click="
            openURLInNewWindow(
              'https://studenthub.technik.fhnw.ch/api/studenthub/anmeldungen',
            )
          "
          >API öffnen
          <font-awesome-icon icon="fa-solid fa-arrow-up-right-from-square"
        /></span>
      </div>
      <textarea
        :onchange="studenthubApplicationsChanged"
        :class="[
          errors.studenthubApplicationsParseError
            ? 'border border-red-500'
            : '',
        ]"
        class="font-mono w-full h-32 dark:bg-gray-900 bg-gray-100 p-1 text-xs"
        :value="
          studenthubStore.applications
            ? JSON.stringify(studenthubStore.applications)
            : ''
        "
      />
    </div>
  </BaseModal>
</template>

<script lang="ts">
import { openURLInNewWindow } from "../../helpers";
import { useClassesStore } from "../../stores/classes";
import { useClassVersionStore } from "../../stores/ClassVersion";
import { useConfigStore } from "../../stores/config";
import { usePlanningStore } from "../../stores/planning";
import { useStateStore } from "../../stores/state";
import { useStudenthubStore } from "../../stores/studenthub";
import BaseModal from "./BaseModal.vue";

type SemesterVersionEntry = {
  disabled: boolean;
  title: string;
  key: [string, string];
};

export default {
  name: "SettingsModal",
  components: { BaseModal },
  setup() {
    const studenthubStore = useStudenthubStore();
    const stateStore = useStateStore();
    const classVersionStore = useClassVersionStore();
    const configStore = useConfigStore();
    const classesStore = useClassesStore();
    const planningStore = usePlanningStore();

    return {
      studenthubStore,
      stateStore,
      classVersionStore,
      configStore,
      classesStore,
      planningStore,
      openURLInNewWindow,
    };
  },
  data() {
    return {
      errors: {
        studenthubApplicationsParseError: false,
        studenthubStudentParseError: false,
      },
    };
  },
  computed: {
    hideCompletedClasses: {
      get(): boolean {
        return this.stateStore.hideCompletedClasses;
      },
      set(value: boolean) {
        this.stateStore.updateHideCompletedClasses(value);
      },
    },
    selectedClassVersion: {
      get(): [string, string] {
        const selected = this.classVersionStore;
        return [selected.semester ?? "", selected.version ?? ""];
      },
      set(value: [string, string]) {
        if (this.planningStore.chosen.length > 0) {
          const isSure = confirm(
            "Es ist keine gute Idee die Version des Stundenplans zu ändern, währendem dieser Module eingetragen hat.\n\n" +
              "Mache einen neuen, leeren Plan oder nimm in kauf, dass deine geplanten Module verschwinden.\n\n" +
              "Willst du trotzdem fortfahren?",
          );
          if (!isSure) {
            if (this.$refs.classVersionSelect)
              // @ts-expect-error The value prop exists here, no worries :)
              this.$refs.classVersionSelect.value = this.selectedClassVersion;
            return;
          }
        }

        const semester = value[0];
        const version = value[1];

        useClassVersionStore().useSemesterVersion(semester, version);
        this.planningStore.saveChosen();

        this.classVersionStore.useSemesterVersion(semester, version);
      },
    },
    semesterVersions(): SemesterVersionEntry[] {
      const out = [] as SemesterVersionEntry[];
      this.classVersionStore.semesterVersions.forEach((sem) => {
        out.push({ disabled: true, title: sem.semester, key: ["", ""] });
        sem.versions.forEach((version) =>
          out.push({
            disabled: false,
            title: `(${sem.semester}) ${version}`,
            key: [sem.semester, version],
          }),
        );
      });
      return out;
    },
  },
  methods: {
    close() {
      this.stateStore.showingSettings = false;
    },
    studenthubApplicationsChanged(event: Event) {
      const raw = (event.target as HTMLInputElement).value as string;
      this.errors.studenthubApplicationsParseError = false;
      if (raw.length == 0) {
        this.studenthubStore.setApplicationsData(null);
        return;
      }
      let parsed;
      try {
        parsed = JSON.parse(raw);
      } catch (e) {
        this.studenthubStore.setApplicationsData(null);
        this.errors.studenthubApplicationsParseError = true;
        console.error(e);
        return;
      }
      if (parsed === undefined) {
        this.studenthubStore.setApplicationsData(null);
        this.errors.studenthubApplicationsParseError = true;
        return;
      }
      this.studenthubStore.setApplicationsData(parsed);
    },
    studenthubStudentChanged(event: Event) {
      const raw = (event.target as HTMLInputElement).value as string;
      this.errors.studenthubStudentParseError = false;
      if (raw.length == 0) {
        this.studenthubStore.setStudentData(null);
        return;
      }
      let parsed;
      try {
        parsed = JSON.parse(raw);
      } catch (e) {
        this.studenthubStore.setStudentData(null);
        this.errors.studenthubStudentParseError = true;
        console.error(e);
        return;
      }
      if (parsed === undefined) {
        this.studenthubStore.setStudentData(null);
        this.errors.studenthubStudentParseError = true;
        return;
      }
      this.studenthubStore.setStudentData(parsed);
    },
  },
};
</script>
