<template>
  <div class="transaction-update" v-if="account && transaction">
    <transaction-create :account="account" :transaction="transaction" />
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator'
import { Getter } from 'vuex-class'
import bus, { SYNC } from '@/utils/bus-event'
import IAccount from '@/models/IAccount'
import ITransaction from '@/models/ITransaction'
import accountService from '@/services/AccountService'
import transactionService from '@/services/TransactionService'
import notif from '@/utils/notif'

@Component({
  components: {
    'transaction-create': () => import('@/components/TransactionCreate.vue')
  }
})
export default class TransactionUpdate extends Vue {
  @Prop({ type: String, required: true })
  public id!: string
  public transaction: ITransaction | null = null
  public account: IAccount | null = null

  public created(): void {
    this.getData()
    bus.$on(SYNC, this.getData)
  }

  public async getData(docIds?: string[]): Promise<void> {
    if (docIds && !docIds.find((i: string) => i === this.id)) {
      return
    }
    this.transaction = await transactionService.get(this.id)
    if (!this.transaction) {
      this.$router.push({ name: 'home' })
      notif.error('Compte inexistant.')
      return
    }
    this.account = await accountService.get(this.transaction.accountId)
  }
}
</script>
