<template>
  <MainTemplate>
    <template #headerInsert>
      <RouterLink to="../" class="text-primary">zurück zur Liste</RouterLink>
    </template>
    <template #topBar>
      <div class="flex flex-row items-center justify-between pt-5 pb-3 px-7">
        <h1 class="font-bold text-xl h-8">Nutzer {{ user?.username }} - Berechtigungen bearbeiten</h1>
      </div>
    </template>
    <template #main>
      <p>Hinweis: Berechtigungen von Nutzer und Rolle sind ergänzend.</p>
      <Spinner v-if="loading == 'loading'" class="mx-auto" />
      <p v-else-if="loading == 'failed'">laden fehlgeschlagen</p>
      <Permission
        v-else-if="user != null"
        :permissions="user.permissions"
        :status="status"
        @savePermissions="triggerUpdate"
      />
    </template>
  </MainTemplate>
</template>

<script setup lang="ts">
import { defineComponent } from "vue";
import { mapState, mapActions } from "pinia";
import MainTemplate from "@/templates/Main.vue";
import Permission from "@/components/admin/Permission.vue";
import Spinner from "@/components/Spinner.vue";
import { useUserStore } from "@/stores/admin/user/user";
import type { PermissionObject } from "@/types/permissionTypes";
import type { UserViewModel } from "@/viewmodels/admin/user/user.models";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    id: String,
  },
  data() {
    return {
      loading: "loading" as "loading" | "fetched" | "failed",
      status: null as null | "loading" | { status: "success" | "failed"; reason?: string },
      user: null as null | UserViewModel,
      timeout: null as any,
    };
  },
  mounted() {
    this.fetchItem();
  },
  beforeUnmount() {
    try {
      clearTimeout(this.timeout);
    } catch (error) {}
  },
  methods: {
    ...mapActions(useUserStore, ["fetchUserById", "updateActiveUserPermissions"]),
    fetchItem() {
      this.fetchUserById(parseInt(this.id ?? ""))
        .then((result) => {
          this.user = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    triggerUpdate(e: PermissionObject) {
      if (this.user == null) return;
      this.status = "loading";
      this.updateActiveUserPermissions(this.user.id, e)
        .then(() => {
          this.fetchItem();
          this.status = { status: "success" };
        })
        .catch((err) => {
          this.status = { status: "failed" };
        })
        .finally(() => {
          this.timeout = setTimeout(() => {
            this.status = null;
          }, 2000);
        });
    },
  },
});
</script>
