<template>
  <div class="transaction-new">
    <div v-if="!account">
      no account
      <br />
      {{ id }} - {{ account }}
    </div>
    <div v-else-if="transaction">
      <transaction-create :account="account" :transaction="transaction" />
    </div>
  </div>
</template>

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

const today: Date = new Date()

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

  public async created(): Promise<void> {
    if (this.id) {
      this.account = await accountService.get(this.id)
      if (this.account) {
        this.transaction = await transactionService.getNew(
          this.user,
          this.account
        )
      }

      try {
        if ('geolocation' in navigator) {
          getCurrentPosition().then(({ coords }) => {
            mapService
              .getLocation({
                lat: coords.latitude,
                lon: coords.longitude
              })
              .then((place) => {
                if (!this.transaction) {
                  return
                }
                this.$set(this.transaction, 'location', {
                  lat: coords.latitude,
                  lon: coords.longitude,
                  place
                })
              })
          })
        }
      } catch (error) {
        // tslint:disable-next-line: no-console
        console.error(error)
      }
    }
  }
}
</script>

<style scoped>
.help {
  text-align: left;
}
</style>
