<template>
  <div>
    <div class="d-flex justify-content-between">
      <div class="flex-shrink-0 mr-4">{{ label }}</div>
      <div>{{ date }}</div>
    </div>
    <div class="d-flex justify-content-between align-items-center mt-3">
      <div class="flex-shrink-0 mr-4">Door</div>
      <user-avatar v-if="user" :user="user">{{ userLabel }}</user-avatar>
      <template v-else>{{ userLabel }}</template>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
import { namespace } from 'vuex-class';

import UserAvatar from './user-avatar.vue';

import { User } from '../types/api';
import AssetApi from '../api/asset-api';

const UserStore = namespace('cmsUser');

@Component({
  components: {
    UserAvatar
  }
})
export default class EditedData extends Vue {
  @Prop(String) readonly label!: string;
  @Prop(String) readonly date!: string;
  @Prop(String) readonly username!: string;

  @UserStore.State('items') readonly users!: User[];
  @UserStore.State('initialized') readonly initialized!: boolean;

  user: User | null = null;

  async mounted() {
    if (this.initialized) {
      await this.getUser();
    }
  }

  async getUser() {
    if (this.users.length && this.username) {
      const user = this.users.find(user => user.name === this.username);

      if (user && user.avatar) {
        this.user = user;
        user.avatar = await AssetApi.getAssetById(user.avatar.id);
      }
    }
  }

  get userLabel(): string {
    return this.username?.replace('Bootstrapped user: ', '') || '-';
  }

  @Watch('initialized')
  async onInitializedChange() {
    await this.getUser();
  }
}
</script>
