<template>
  <MainTemplate>
    <template #headerInsert>
      <RouterLink to="../" class="text-primary">zurück zur Liste (abbrechen)</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">Rolle {{ role?.role }} - Berechtigungen bearbeiten</h1>
      </div>
    </template>
    <template #main>
      <Spinner v-if="loading == 'loading'" class="mx-auto" />
      <p v-else-if="loading == 'failed'">laden fehlgeschlagen</p>
      <Permission
        v-else-if="role != null"
        :permissions="role.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 { useRoleStore } from "@/stores/admin/user/role";
import Permission from "@/components/admin/Permission.vue";
import Spinner from "@/components/Spinner.vue";
import type { PermissionObject } from "@/types/permissionTypes";
import type { RoleViewModel } from "@/viewmodels/admin/user/role.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 },
      role: null as null | RoleViewModel,
      timeout: null as any,
    };
  },
  mounted() {
    this.fetchItem();
  },
  beforeUnmount() {
    try {
      clearTimeout(this.timeout);
    } catch (error) {}
  },
  methods: {
    ...mapActions(useRoleStore, ["fetchRoleById", "updateActiveRolePermissions"]),
    fetchItem() {
      this.fetchRoleById(parseInt(this.id ?? ""))
        .then((result) => {
          this.role = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    triggerUpdate(e: PermissionObject) {
      if (this.role == null) return;
      this.status = "loading";
      this.updateActiveRolePermissions(this.role.id, e)
        .then(() => {
          this.fetchItem();
          this.status = { status: "success" };
        })
        .catch((err) => {
          this.status = { status: "failed" };
        })
        .finally(() => {
          this.timeout = setTimeout(() => {
            this.status = null;
          }, 2000);
        });
    },
  },
});
</script>
