<template>
  <article class="account-share message is-success is-medium" v-if="show">
    <div class="message-header">
      <p>Partagez le compte</p>
      <button class="delete" v-if="canClose" aria-label="close" @click="hide"></button>
    </div>
    <div class="message-body">
      <button class="button is-primary is-medium" @click="share" v-if="canShareAPI">Partager</button>
      <div class="field is-grouped is-grouped-centered" v-else>
        <div class="field" :class="{ 'has-addons': canClipboard }">
          <div class="control">
            <input class="input" type="text" readonly :value="accountUrl" />
          </div>
          <div class="control" if="canClipboard">
            <a href="#" class="button is-primary" @click.prevent="copy">Copier</a>
          </div>
        </div>
      </div>
      <hr />
      <div class="qr-code">
        <p>ou via ce QR code :</p>
        <qr-code :value="accountUrl" />
      </div>
    </div>
  </article>
</template>

<script lang="ts">
declare const navigator: any
import { Component, Vue, Prop } from 'vue-property-decorator'
import { Getter } from 'vuex-class'
import IAccount from '@/models/IAccount'
import IUser from '@/models/IUser'
import notif from '@/utils/notif'
import QrCode from '@xkeshi/vue-qrcode'

@Component({
  components: {
    'qr-code': QrCode
  }
})
export default class Home extends Vue {
  @Getter
  public user!: IUser | null
  @Prop({ type: Object, required: true })
  public account!: IAccount
  @Prop({ type: Boolean, default: true })
  public canClose!: boolean
  public show: boolean = true

  public hide(): void {
    if (this.canClose) {
      this.show = false
    }
  }

  public share(): void {
    if (this.canShareAPI) {
      navigator.share({
        title: `Vaquant - Compte ${this.account.name}`,
        text: `${this.username} vous invite sur Vaquant pour gérer vos dépenses sur le compte ${this.account.name}.`,
        url: this.accountUrl
      })
    }
  }

  public async copy(): Promise<void> {
    if (this.canClipboard) {
      await navigator.clipboard.writeText(this.accountUrl)
      notif.success('Adresse copiée')
    }
  }

  public get accountUrl(): string {
    let url = window.location.href.replace('/setting', '')
    if (this.account.isPublic) {
      url = `${url}/public`
    }
    return url
  }

  public get username(): string {
    if (!this.user) {
      return ''
    }
    return (
      `${this.user.firstname} ${this.user.lastname}`.trim() || this.user.email
    )
  }

  public get canShareAPI(): boolean {
    return !!navigator.share
  }

  public get canClipboard(): boolean {
    return !!navigator.clipboard
  }
}
</script>

<style lang='scss' scoped>
$padding-fab: 24px;

.is-fab {
  bottom: $padding-fab;
  position: fixed;
  right: $padding-fab;
}

.fab-margin {
  margin: calc(#{$padding-fab} * 2) 0;
}

.qr-code {
  canvas {
    margin: 1em 0;
  }
}
</style>
