<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>
      <Spinner v-if="loadingSingle == 'loading'" class="mx-auto" />
      <p v-else-if="loadingSingle == 'failed'">laden fehlgeschlagen</p>
      <Permission
        v-else
        :permissions="user?.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 Permission from "@/components/admin/Permission.vue";
import Spinner from "@/components/Spinner.vue";
import { useUserStore } from "@/stores/admin/user";
import type { PermissionObject } from "@/types/permissionTypes";
</script>

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