<!-- components/Profile.vue -->
<template>
  <div>
    <section class="hero is-primary">
      <div class="hero-body">
        <div class="container has-text-centered">
          <div class="clearfix">
            <b-img left style="margin-right: 20px;" src="https://picsum.photos/160/160/?image=58"
                   alt="Left image"></b-img>
            <h2 class="title" v-if="profile.nickname">
              {{ profile.nickname }}
            </h2>
            <h2 class="title" v-else-if="profile.first_name">
              {{ profile.first_name }}&nbsp;{{ profile.last_name }}
            </h2>
            <h2 class="title" v-else>
              {{ profile.email }}
            </h2>

            <p>
              <font-awesome-icon icon="id-badge"/>
              <span v-b-tooltip.hover :title="$t('external user')" v-if="profile.external_user">&nbsp;{{ profile.external_user_id }}&nbsp;
                (<font-awesome-icon :icon="['fab', 'openid']" />)</span>
              <span v-b-tooltip.hover :title="$t('internal user')" v-else>&nbsp;{{ profile.id }}&nbsp;
                (<font-awesome-icon :icon="['far', 'dot-circle']"/>)</span>
            </p>

            <p>
              <font-awesome-icon icon="envelope"/>&nbsp;{{ profile.email }}
              <a class="badge badge-pill badge-info">
                <font-awesome-icon icon="pencil-alt"/>
              </a>
            </p>

            <p v-if="!formEditField['nickname'] && profile.nickname">
              <font-awesome-icon v-b-tooltip.hover :title="$t('nickname')" icon="user-tag"/>&nbsp;{{ profile.nickname }}
              <a class="badge badge-pill badge-info"
                 @click="()=>{form.nickname=profile.nickname; formEditField['nickname']=true;}">
                <font-awesome-icon icon="pencil-alt"/>
              </a>
            </p>
            <ValidationProvider v-slot="v" rules="required" v-else>
            <b-input-group style="max-width: 50%;"  size="sm">

              <b-form-input name="nickname"
                            v-model="form.nickname"
                            class="form-control" type="text"
                            :placeholder="$t('set_your_nickname') + ' ('+profile.nickname +')'"></b-form-input>
              <b-input-group-append>
                <b-button :disabled="v.errors.length > 0"
                          @click="updateProfile('nickname')"
                          variant="outline-success">
                  <font-awesome-icon icon="check"></font-awesome-icon>
                </b-button>
              </b-input-group-append>
            </b-input-group>
            </ValidationProvider>


          </div>

          <hr/>

          <p><strong>{{ $t('first_name') }}:&nbsp</strong>{{ profile.first_name }}</p>
          <p><strong>{{ $t('last_name') }}:&nbsp</strong>{{ profile.last_name }}</p>

          <hr/>
          <!--<p v-if="profile.role"><strong>{{$t('role')}}:&nbsp</strong>{{profile.role}}</p>-->
          <p><strong>{{ $t('role') }}:&nbsp</strong><span v-if="profile.role">{{ profile.role }}</span><span
              v-else>{{ $t('no specifc role') }}</span></p>
          <p><strong>{{ $t('groups') }}:&nbsp</strong><span v-for="g in profile.groups">{{ g.name }}, </span></p>
          <p><strong>{{ $t('permissions') }}:&nbsp</strong></p>
          <ul>
            <li v-for="p in profile.effective_permissions">{{ p.name }}</li>
          </ul>

          <hr/>

          <div>
            <button class="lang-btn" v-for="entry in languages" :key="entry.title"
                    @click="changeLocale(entry.language)">
              <flag :iso="entry.flag" v-bind:squared="false"/>
              {{ entry.title }}
            </button>
          </div>
          <p class="title">Token validity ({{ tokenValidity }})</p>
          <p class="title">Refresh token validity ({{ refreshTokenValidity }})</p>
          <p class="title">access_token ({{ access_token }})</p>
          <p>{{ profile.id }}</p>
          <p class="subtitle error-msg">{{ errorMsg }}</p>
        </div>
      </div>
    </section>
    {{ profile }}
  </div>
</template>

<script>
import {EventBus} from '@/utils';
import {getRemainingJwtValiditySeconds} from '@/utils';
import getRepository from '@/api/RepositoryFactory';
//import { extend } from 'vee-validate';
import '@/validation';


const userRepository = getRepository('user');

export default {
  data() {
    return {
      email: '',
      errorMsg: '',
      tokenValidity: -1,
      refreshTokenValidity: -1,
      formEditField: {},
      languages: [
        {flag: 'us', language: 'en', title: 'English'},
        {flag: 'es', language: 'es', title: 'Español'},
        {flag: 'de', language: 'de', title: 'Deutsch'},
      ],
      form: {
        first_name: '',
        last_name: '',
        nickname: '',
        email: '',
      },
    };
  },
  methods: {
    authenticate() {
      this.$store.dispatch('login', {email: this.email, password: this.password})
          .then(() => this.$router.push('/'));
    },
    updateProfile(fieldName) {
      this.$parent.$data.isLoading = true;
      this.$set(this.formEditField, fieldName, false);
      const data = {};
      data[fieldName] = this.form[fieldName];
      userRepository.updateProfile(data)
          .then(() => {
            this.$store.dispatch('loadProfile')
                .then(() => {
                  this.$parent.$data.isLoading = false;
                });
          });
    },
    changeLocale(locale) {
      this.$i18n.locale = locale;
      // Vue.$moment.locale(locale);
    },
  },
  mounted() {
    EventBus.$on('failedLoadingProfile', (msg) => {
      this.errorMsg = msg;
    });
    this.$store.dispatch('loadProfile');

    this.$nextTick(() => {
      window.setInterval(() => {
        this.tokenValidity = getRemainingJwtValiditySeconds(this.$store.state.access_token);
        this.refreshTokenValidity = getRemainingJwtValiditySeconds(this.$store.state.refresh_token);
      }, 1000);
    });


  },
  beforeDestroy() {
    EventBus.$off('failedLoadingProfile');
  },
  computed: {
    profile() {
      return this.$store.state.profile;
    },
    access_token() {
      return this.$store.state.access_token;
    },
  },
};
</script>

<style lang="scss">
.error-msg {
  color: red;
  font-weight: bold;
}

.lang-btn {
  padding: 15px;
  border: 2px solid green;
  font-size: 18px;
  margin: 15px;
}
</style>
