<template>
  <div class="account-user-new">
    <h3 v-if="showTitle" class="subtitle is-3">{{ $tc('account.friends', localeUsers.length, { count: localeUsers.length }) }}</h3>
    <user-new v-if="user && defaultUser" v-model="user" />
    <div v-for="(user, k) in localeUsers" :key="k">
      <user-new v-model="localeUsers[k]" @remove="() => remove(k)" />
    </div>
    <br />
    <div class="field has-addons">
      <div class="control">
        <input
          class="input"
          type="text"
          placeholder="nouvel ami"
          v-model="newUserId"
          @keyup.enter.prevent="newUser"
        />
      </div>
      <div class="control">
        <button type="button" class="button is-primary" @click.prevent="newUser">ajouter</button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Model, Prop, Vue, Watch } from 'vue-property-decorator'
import { Getter } from 'vuex-class'
import IUser from '@/models/IUser'

@Component({
  components: {
    'user-new': () => import('@/components/UserNew.vue')
  }
})
export default class HelloWorld extends Vue {
  @Getter
  public user!: IUser | null
  @Model('input', { type: Array, required: true })
  public users!: IUser[]
  @Prop({ type: Boolean, default: true })
  public defaultUser!: boolean
  @Prop({ type: Boolean, default: true })
  public showTitle!: boolean
  public localeUsers: IUser[] = []
  public userId: string = ''
  public newUserId: string = ''

  public mounted(): void {
    this.localeUsers = this.users
  }

  public newUser(): void {
    if (!this.newUserId) {
      return
    }
    this.localeUsers.push({
      userId: this.newUserId,
      email: '',
      premium: this.user ? this.user.premium : false,
      slugEmail: '',
      alias: this.newUserId,
      firstname: '',
      lastname: ''
    })
    this.newUserId = ''
  }

  public remove(index: number): void {
    this.localeUsers = this.localeUsers.filter(
      (u: IUser, i: number) => i !== index
    )
  }

  public removeUser(): void {
    this.localeUsers.pop()
  }

  @Watch('users')
  public onUsersChange(users: IUser[]): void {
    this.localeUsers = users
  }

  @Watch('localeUsers')
  public onUserChange(users: IUser[]): void {
    this.$emit('input', users)
  }
}
</script>
