<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">Rolle {{ role?.role }} - Berechtigungen bearbeiten</h1>
      </div>
    </template>
    <template #main>
      <Spinner v-if="loadingSingle == 'loading'" class="mx-auto" />
      <p v-else-if="loadingSingle == 'failed'">laden fehlgeschlagen</p>
      <Permission
        v-else
        :permissions="role?.permissions"
        :status="updateStatus"
        @savePermissions="triggerPermissionUpdate"
        @abortPermissions="$router.push('../')"
      />
    </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/role";
import Permission from "@/components/admin/Permission.vue";
import Spinner from "@/components/Spinner.vue";
import type { PermissionObject } from "@/types/permissionTypes";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    id: String,
  },
  computed: {
    ...mapState(useRoleStore, ["role", "loadingSingle", "updateStatus"]),
  },
  mounted() {
    this.resetStatus();
    this.fetchRoleById(parseInt(this.id ?? ""));
  },
  methods: {
    ...mapActions(useRoleStore, ["fetchRoleById", "updateActiveRolePermissions", "resetStatus"]),
    triggerPermissionUpdate(e: PermissionObject) {
      this.updateActiveRolePermissions(e);
    },
  },
});
</script>
