<template>
  <div>
    <b-form-group label="Alegeți coloanele care pot conține numere de telefon:" v-slot="{ ariaDescribedby }">
      <b-form-checkbox-group
          v-model="phoneColumns"
          :options="columnNames"
          :disabled="!editable"
          :aria-describedby="ariaDescribedby"
      ></b-form-checkbox-group>
    </b-form-group>
    <b-form-group label="Compuneți template-ul mesajului de expediat" v-slot="{ ariaDescribedby }">
      <b-form-textarea
          v-model="liveTemplateText"
          :placeholder="`Folosiți sintaxa \${numeColoana} pentru a prelua textul coloanei respective în mesajul creat pentru fiecare linie (de exemplu, \${${columnNames ? columnNames[0].text : 'prima-coloana'}})`"
          :state="templateTextValid"
          :style="{'overflow': 'auto'}"
          :disabled="!editable"
          rows="3"
          max-rows="6"
      ></b-form-textarea>
      <component :is="templateTextValid ? 'b-form-valid-feedback' : 'b-form-invalid-feedback'">
        {{ liveTemplateText.length }} / {{ maxMessageSize }}
      </component>
    </b-form-group>
    <div class="q-pa-md">
      <q-table
          class="vscroll-table"
          virtual-scroll
          :virtual-scroll-sticky-size-start="48"
          row-key="index"
          :data="tableData"
          :columns="tableColumns"
          :pagination.sync="pagination"
          :rows-per-page-options="[0]"
          :hide-bottom="true"
          label="Alegeți / editați mesajele de expediat"
      >
        <template v-slot:header-cell-selected="props">
          <q-th :props="props">
            <q-checkbox
                v-model="rowSelection"
                true-value="all"
                false-value="none"
                intermediate-value="some"
                :disabled="!editable"
            />
          </q-th>
        </template>
        <template v-slot:body-cell-selected="props">
          <q-td :props="props">
            <span class="small">{{ props.row.index + 1 }}</span>
            <br/>
            <q-checkbox
                v-model="selectedRows[props.row.index]"
                :disabled="!editable"
            />
          </q-td>
        </template>
        <template v-slot:body-cell-index="props">
          <q-td :props="props">
            <message-line-handler
                :template-text="templateText"
                :row="props.row"
                :column-name-map="columnNameMap"
                :phone-columns="phoneColumns"
                :overridden-messages="overriddenMessages"
                :disabled="!editable"
                :max-message-size="maxMessageSize"
            />
          </q-td>
        </template>
      </q-table>
      <div class="q-pa-md" v-if="!prepareMessages">
        <q-btn @click="prepareMessages = true" color="primary" icon-right="all_inbox" label="Pregătește mesajele" :disabled="!templateTextValid"/>
      </div>
      <div class="q-pa-md" v-else>
        <message-dispatcher :editable="editable" :messages="lazyAllMessages" @sending-started="editable = false" @sending-finished="editable = true"/>
      </div>
    </div>
  </div>
</template>

<script>

module.exports = {
  name: "SheetSmsCreator",
  methods: {
  },
  data: function() {
    var validColumns = this.sheet.data[0].filter(e => e).map(
        (columnName, index) => {
          return {text: columnName, value: index};
        }
    );

    return {
      columnNames: validColumns,
      phoneColumns: guessPhoneColumns(this.sheet, validColumns),
      selectedRows: new Array(this.sheet.data.length - 1).fill(true),
      liveTemplateText: "",
      templateText: "",
      overriddenMessages: [],
      pagination: { rowsPerPage: 0 },
      prepareMessages: false,
      editable: true
    };

  },
  watch:
  {
    liveTemplateText: delay(function() { this.templateText = this.liveTemplateText; }, 250)
  },
  computed:
  {
    rowSelection: {
      get() {
        var selectedCount = this.selectedRows.filter(v => v).length;
        return selectedCount === 0 ? "none" : selectedCount === this.tableData.length ? "all" : "some";
      },
      set(newValue) {
        var newSelectedRows = new Array(this.selectedRows.length);
        switch (newValue) {
          case "all":
            newSelectedRows.fill(true);
            break;
          case "none":
            newSelectedRows.fill(false);
        }
        this.selectedRows = newSelectedRows;
      }
    },
    lazyAllMessages() {
      if (!this.prepareMessages) {
        return [];
      }
      var messages = [];
      var data = this.sheet.data;
      var templateText = this.templateText;
      var columnNameMap = this.columnNameMap;
      var overriddenMessages = this.overriddenMessages;
      this.selectedRows.forEach((rowSelected, rowIndex ) => {
        if (rowSelected) {
          var row = data[rowIndex + 1];
          getCandidatePhoneNumbers(row, this.phoneColumns).forEach(candidatePhoneNumber => {
            var preparedNumber = prepareNumber(candidatePhoneNumber);
            if (preparedNumber != null && preparedNumber.isValid) {
              messages.push({
                to: preparedNumber.e164,
                destinationType: preparedNumber.destinationType,
                valid: preparedNumber.isValid,
                getText() {
                  return overriddenMessages[rowIndex] || applyTemplate(templateText, columnNameMap, {data: row});
                }
              });
            }
          });
        }
      });
      return messages;
    },
    templateTextValid() {
      return this.liveTemplateText.length > 0 && this.liveTemplateText.length <= this.maxMessageSize;
    },
    columnNameMap() {
      var columnNameMap = new Map();
      this.columnNames.forEach(column => {
        columnNameMap.set("${" + column.text.toLowerCase() + "}", column.value);
      });
      return columnNameMap;
    },
    tableColumns() {
      return [
        {
          name: "selected",
          label: "Selectat",
          align: "center",
          field: row => this.selectedRows[row.index]
        },
        {
          name: "index",
          label: "Mesaj",
          align: "left",
          field: row => row.index
        },
        ...this.columnNames.map(c => {
          return {
            name: "c" + c.value,
            label: c.text,
            sortable: true,
            align: "left",
            field: row => row.data[c.value]
          }
        })
      ];
    },
    tableData() {
      return this.sheet.data.slice(1).map((rowData, index) => { // skip first row
          return {data: rowData, index: index};
      });
    }
  },
  props: {
    sheet: Object,
    maxMessageSize: Number
  }
}

</script>

<style lang="css">

.vscroll-table {
  height: 400px;
}

.vscroll-table  tr th {
  position: sticky;
  /* higher than z-index for td below */
  z-index: 2;
  /* bg color is important; just specify one */
  background: #fff;
}

/* this will be the loading indicator */
.vscroll-table  thead tr:last-child th {
  /* height of all previous header rows */
  top: 48px;
  /* highest z-index */
  z-index: 3
}

.vscroll-table  thead tr:first-child th {
  top: 0;
  z-index: 1;
}

.vscroll-table  tr:first-child th:nth-child(1), .vscroll-table  tr:first-child th:nth-child(2) {
  /* highest z-index */
  z-index: 3;
}

.vscroll-table td:nth-child(1), .vscroll-table td:nth-child(2)  {
  z-index: 1;
  background-color: #fff !important
}

.vscroll-table td:nth-child(1), .vscroll-table th:nth-child(1) {
  position: sticky;
  left: 0;
  min-width: 50px;
  max-width: 50px;
}

.vscroll-table td:nth-child(2), .vscroll-table th:nth-child(2) {
  position: sticky;
  left: 50px;
  min-width: 450px;
  max-width: 450px;
}

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

</style>