<template>
  <div id="multi-sms">
    <b-form-textarea
        id="liveTemplateText"
        v-model="liveTemplateText"
        :placeholder="`Compuneți mesajul care va fi trimis la unul sau mai multe numere destinatare`"
        :state="templateTextValid"
        :disabled="!editable"
        rows="3"
    ></b-form-textarea>
    <component :is="templateTextValid ? 'b-form-valid-feedback' : 'b-form-invalid-feedback'">
      {{ liveTemplateText.length }} / {{ maxMessageSize }}
    </component>
    <b-form-textarea
        id="liveRawNumbers"
        v-model="liveRawNumbers"
        :placeholder="`Introduceți numerele de telefon, separate cu ',' sau ';' sau spatiu`"
        :disabled="!editable"
        rows="3"

    ></b-form-textarea>
    <div class="q-pa-md" v-if="templateTextValid && numbers.length > 0">
      <message-dispatcher :editable="editable" :messages="allMessages" @sending-started="editable = false" @sending-finished="editable = true"/>
    </div>
  </div>
</template>

<script>
module.exports = {
  name: 'MultiSms',
  components: {
  },
  props: {
    maxMessageSize: Number
  },
  data: function() {
    return {
      editable: true,
      liveTemplateText: "",
      liveRawNumbers: "",
      templateText: "",
      numbers: []
    }
  },
  methods: {
  },
  computed: {
    templateTextValid() {
      return this.liveTemplateText.length > 0 && this.liveTemplateText.length <= this.maxMessageSize;
    },
    allMessages() {
      var messages = [];
      var content = this.templateText;
      this.numbers.forEach(number => {
        messages.push({
          to: number.e164,
          destinationType: number.destinationType,
          valid: number.isValid,
          getText() {
            return content;
          }
        });
      });
      return messages;
    }
  },
  watch: {
    liveTemplateText: delay(function() { this.templateText = this.liveTemplateText; }, 250),
    liveRawNumbers: delay(function() {
      var numbers = [];
      this.liveRawNumbers.split(/[,;\n ]/).forEach(number => {
        var preparedNumber = prepareNumber(number.trim());
        if (preparedNumber != null && preparedNumber.isValid) {
          numbers.push(preparedNumber);
        }
      });
      if (!checkNumberArrayEquality(numbers, this.numbers)) { // vrosca: avoid assigning until an actual change happens
        this.numbers = numbers;
      }
    }, 500),
  }
}

function checkNumberArrayEquality(a1, a2) {
  if (a1 == null && a2 != null || a1 != null && a2 == null || a1.length !== a2.length) {
    return false;
  }

  var count = a1.length;

  for (var i=0; i<count; i++) {

    if (a1[i].e164 !== a2[i].e164) {

      return false;

    }

  }

  return true;

}
</script>

<style scoped>

#multi-sms {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
}

.row { /* bootstrap - quasar conflict */
  margin: 0;
}

</style>