<template>
  <div>
    <q-page
      padding
      class="fit row justify-center content-center items-center q-gutter-sm"
    >
      <q-card class="col-12">
        <q-card-section
          class="fit row justify-start content-center items-center"
        >
          <div class="col-12 text-center text-h6">Benutzereinstellungen</div>
        </q-card-section>
        <MainUserSettings :user="currentUser" @update:user="updateUser" />
      </q-card>
      <div class="col-12 text-left text-h6">Aktive Sessions:</div>
      <sessions
        v-for="(session, index) in sessions"
        :key="'session' + index"
        :session="session"
      />
    </q-page>
  </div>
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  onBeforeMount,
  ref
} from '@vue/composition-api';
import CircularProgress from 'components/loading/CircularProgress.vue';
import Sessions from '../components/settings/Sessions.vue';
import MainUserSettings from '../components/settings/MainUserSettings.vue';
import { Store } from 'vuex';
import { StateInterface } from 'src/store';
import setLoadingBar from 'components/loading';

export default defineComponent({
  // name: 'PageName'
  components: { CircularProgress, Sessions, MainUserSettings },
  setup(_, { root }) {
    const store = <Store<StateInterface>>root.$store;

    onBeforeMount(() => {
      store.dispatch('session/getSessions').catch(error => {
        console.warn(error);
      });
    });

    const currentUser = ref(<FG.User>store.state.user.currentUser);
    const sessions = computed(() => store.state.session.sessions);
    const loading = computed(
      () => store.state.session.loading || store.state.user.loading > 0
    );
    function updateUser(value: FG.User) {
      store.dispatch('user/updateUser', value).catch(error => {
        console.warn(error);
      });
    }

    setLoadingBar(loading);

    return {
      currentUser,
      sessions,
      updateUser
    };
  }
});
</script>
