<template>
  <q-card class="col-12">
    <q-card-section class="fit row justify-start content-center items-center">
      <div class="col-xs-12 col-sm-6 text-center text-h6">Benutzereinstellungen</div>
      <div class="col-xs-12 col-sm-6 q-pa-sm">
        <UserSelector v-model="user" />
      </div>
    </q-card-section>
    <MainUserSettings
      :user="user"
      :removeable="canDelete && !isCurrentUser"
      @update:user="updateUser"
      @remove="remove"
    />
  </q-card>
</template>

<script lang="ts">
import { computed, defineComponent, ref, onMounted } from 'vue';
import { hasPermission, useMainStore, useUserStore } from '@flaschengeist/api';
import { Notify } from 'quasar';
import { PERMISSIONS } from '../permissions';

import MainUserSettings from './settings/MainUserSettings.vue';
import UserSelector from './UserSelector.vue';

export default defineComponent({
  name: 'UpdateUser',
  components: { UserSelector, MainUserSettings },
  setup() {
    const mainStore = useMainStore();
    const userStore = useUserStore();

    const user = ref(mainStore.currentUser);
    const canDelete = computed(() => hasPermission(PERMISSIONS.DELETE));
    const isCurrentUser = computed(() => user.value.userid === mainStore.currentUser.userid);

    onMounted(() => {
      void userStore.getUsers(true);
    });

    async function updateUser(value: FG.User) {
      await userStore.updateUser(value);
      user.value = value;
      Notify.create({
        group: false,
        type: 'positive',
        message: 'Änderungen gespeichert',
        timeout: 4000,
        progress: true,
        actions: [{ icon: 'mdi-close', color: 'white' }],
      });
    }

    async function remove() {
      await userStore.deleteUser(user.value);
      user.value = mainStore.currentUser;
    }

    return {
      canDelete,
      isCurrentUser,
      remove,
      user,
      updateUser,
    };
  },
});
</script>

<style scoped></style>
