<template>
      <div v-if="emails" class="q-gutter-y-sm">
        <div
          v-for="(email, index) in localEmails"
          :key="index"
          class="row items-center"
        >
          <q-input
            class="col-11"
            v-model="localEmails[index]"
            filled
            :label="`${$t('email')} №${index + 1}`"
            :rules="rules"
          />
          <div class="col-1 row items-center justify-center">
            <q-btn
              outline
              class="q-mb-md"
              color="primary"
              icon="delete"
              style="width: 48px;"
              @click="() => removeEmail(index)"
            >
            </q-btn>
          </div>
        </div>
        <q-btn
          :label="$t('addEmail')"
          color="primary"
          icon="add"
          @click="addEmail"
        >
        </q-btn>
      </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import {
  noEmptyValueRule,
  validEmailRule,
} from '@utils/field-validation/basic';
import cloneDeep from 'lodash/cloneDeep';

@Component
export default class NotificationEmailsEditor extends Vue {
  @Prop() emails: string[];

  noEmptyValueRule = noEmptyValueRule;
  validEmailRule = validEmailRule;
  rules = [noEmptyValueRule, validEmailRule];

  localEmails: string[] = [];
  
  created() {
    this.localEmails = cloneDeep(this.emails);
  }

  addEmail(): void {
    this.localEmails.push('');
    this.$emit('update:emails', this.localEmails);
  }

  removeEmail(index: number): void {
    this.localEmails.splice(index, 1);
    this.$emit('update:emails', this.localEmails);
  }

  beforeDestroy() {
    this.localEmails = this.localEmails.filter(email =>
      this.rules.every(r =>
        r(email) === true
      )
    );
    this.$emit('update:emails', this.localEmails);
  }
}
</script>

<style scoped>

</style>

<i18n>
{
  "ru": {
    "addEmail": "Добавить почтовый ящик",
    "email": "Почта"
  },
  "en": {
    "addEmail": "Add email",
    "email": "Email"
  }
}
</i18n>