<template>
  <h2 class="tool-title">SQL split IN</h2>
  <hr class="mt-5 mb-5">

  <div class="input-group">
    <label for="field_name">Field name</label>
    <input id="field_name" v-model="toolData.fieldName" placeholder="D.ID" type="text">
  </div>

  <div class="input-group">
    <label for="data">Data</label>
    <textarea id="data" v-model="toolData.data" style="height: 150px"></textarea>
  </div>

  <div class="input-group">
    <label for="data_delimiter">Delimiter</label>
    <input id="data_delimiter" v-model="toolData.dataDelimiter" placeholder="," type="text">
  </div>

  <div class="input-group">
    <label>Wrap in quotes</label>

    <div>
      <input id="wrap_in_quotes_no" value="" name="wrap_in_quotes" v-model="toolData.wrapInQuotes" type="radio"> <label for="wrap_in_quotes_no">No</label><br>
      <input id="wrap_in_quotes_single" value="single" name="wrap_in_quotes" v-model="toolData.wrapInQuotes" type="radio"> <label for="wrap_in_quotes_single">Single</label><br>
      <input id="wrap_in_quotes_double" value="double" name="wrap_in_quotes" v-model="toolData.wrapInQuotes" type="radio"> <label for="wrap_in_quotes_double">Double</label>
    </div>
  </div>

  <div class="input-group">
    <label for="chunk_by">Chunk by</label>
    <input id="chunk_by" v-model="toolData.chunkBy" placeholder="900" min="1" type="number">
  </div>

  <hr class="mt-5 mb-5">

  <div class="input-group">
    <label for="result">Result</label>
    <textarea id="result" v-model="toolResult" style="height: 150px"></textarea>
  </div>
</template>

<script>
function arrayChunk(arr, chunkSize) {
  const res = [];
  while (arr.length > 0) {
    const chunk = arr.splice(0, chunkSize);
    res.push(chunk);
  }
  return res;
}

export default {
  data() {
    return {
      toolData: {
        fieldName: '',
        data: '',
        dataDelimiter: '',
        wrapInQuotes: '',
        chunkBy: 900,
      },
    };
  },
  computed: {
    toolResult() {
      let data = this.toolData.data
        .split(this.toolData.dataDelimiter ? this.toolData.dataDelimiter : '\n');

      for (let i = 0; i < data.length; i++) {
        let value = data[i];

        switch (this.toolData.wrapInQuotes) {
          case 'single':
            value = "'" + value.replace("'", "\\'") + "'";
            break;
          case 'double':
            value = '"' + value.replace('"', '\\"') + '"';
            break;
        }

        data[i] = value;
      }

      const chunkBy = this.toolData.chunkBy > 0 ? this.toolData.chunkBy : 1;
      data = arrayChunk(data, chunkBy);

      for (let i = 0; i < data.length; i++) {
        let chunk = data[i];

        data[i] = '(' + chunk.join(',') + ')';
      }

      return '(' + this.toolData.fieldName + ' IN ' + data.join(' OR ' + this.toolData.fieldName + ' IN ') + ')';
    },
  },
}
</script>

<style lang="scss">

</style>