<template>
  <h2 class="tool-title">Str sort lines</h2>
  <hr class="mt-5 mb-5">

  <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>Mode</label>

    <div>
      <input id="sort_mode_alpha" value="alpha" name="sort_mode" v-model="toolData.sortMode" type="radio"> <label for="sort_mode_alpha">alphabetically</label><br>
      <input id="sort_mode_numerically" value="numerically" name="sort_mode" v-model="toolData.sortMode" type="radio"> <label for="sort_mode_numerically">numerically</label><br>
      <input id="sort_mode_by_length" value="by_length" name="sort_mode" v-model="toolData.sortMode" type="radio"> <label for="sort_mode_by_length">by length</label><br>
      <input id="sort_mode_random" value="random" name="sort_mode" v-model="toolData.sortMode" type="radio"> <label for="sort_mode_random">random</label><br>
      <br>
      <input id="sort_mode_reverse" value="random" name="sort_mode_reverse" v-model="toolData.sortModeReverse" type="checkbox"> <label for="sort_mode_reverse">reverse</label>
    </div>
  </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>
export default {
  data() {
    return {
      toolData: {
        data: '',
        sortMode: 'alpha',
        sortModeReverse: false,
      },
    };
  },
  computed: {
    toolResult() {
      let result = []
      const data = this.toolData.data.split('\n');

      switch (this.toolData.sortMode) {
        case 'alpha':
          result = data.sort(function(a, b) {
            return a.localeCompare(b);
          });
          break;
        case 'numerically':
          const collator = new Intl.Collator([], {numeric: true});

          result = data.sort(function(a, b) {
            return collator.compare(a, b);
          });
          break;
        case 'by_length':
          result = data.sort(function(a, b) {
            return a.length - b.length;
          });
          break;
        case 'random':
          result = data.sort(function(a, b) {
            return Math.random() - .5;
          });
          break;
      }

      if (this.toolData.sortModeReverse) {
        result = result.reverse();
      }

      return result.join('\n');
    },
  },
}
</script>

<style lang="scss">

</style>