<template>
  <div class="account-public">Récupération du compte public...</div>
</template>

<script lang="ts">
import Vue from 'vue'
import { Action, Getter } from 'vuex-class'
import { Component, Prop } from 'vue-property-decorator'
import IUser from '@/models/IUser'
import IAccount from '@/models/IAccount'
import notif from '@/utils/notif'
import accountService from '@/services/AccountService'
import couchService from '../../services/CouchService'

@Component
export default class AccountPublic extends Vue {
  @Getter public user!: IUser | null
  @Prop({ type: String, required: true })
  public id!: string
  public account: IAccount | null = null
  @Action
  public addAccountId!: any

  public async mounted(): Promise<void> {
    try {
      if (this.id) {
        this.account = await accountService.get(this.id)
        if (this.account) {
          this.$router.push({ name: 'account', params: { id: this.id } })
          return
        }
      }
    } catch (error) {
      this.account = await accountService.getRemote(this.id)
      if (this.account && this.account.isPublic) {
        this.addAccountId({ accountId: this.id })
        notif.confirm(
          `Récupération du compte public ${this.account.name} en cours...`
        )

        await couchService.initLive()
        this.$router.push({
          name: 'account',
          params: { id: this.id }
        })
        return
      }
      return
    }
  }
}
</script>
