<template>
  <h2 class="tool-title">File base64 encode/decode</h2>
  <hr class="mt-5 mb-5">

  <div class="input-group" v-if="toolData.base64Mode === 'encode'">
    <label for="data">Data</label>
    <input type="file" ref="fileEncodeUpload" @change="encode" />
  </div>
  <div class="input-group" v-if="toolData.base64Mode === 'decode'">
    <label for="data">Data</label>
    <textarea id="data" v-model="toolData.data"></textarea>
  </div>

  <div class="input-group" v-if="toolData.base64Mode === 'encode'">
    <label>Strip mime/type</label>

    <div>
      <input id="strip_mime" name="strip_mime" v-model="toolData.stripMime" v-on:change="encode" type="checkbox"> <label
      for="strip_mime">strip mime</label>
    </div>
  </div>

  <div class="input-group">
    <label>Mode</label>

    <div>
      <input id="base64_mode_encode" value="encode" name="base64_mode" v-model="toolData.base64Mode" type="radio">
      <label for="base64_mode_encode">file -> base64</label><br>
      <input id="base64_mode_decode" value="decode" name="base64_mode" v-model="toolData.base64Mode" type="radio">
      <label for="base64_mode_decode">base64 -> file</label>
    </div>
  </div>

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

  <div class="input-group" v-if="toolData.base64Mode === 'encode'">
    <label for="result">Result</label>
    <MonacoEditor name="result" language="text" :value="toolResult"></MonacoEditor>
  </div>
  <div class="input-group" v-if="toolData.base64Mode === 'decode'">
    <label for="result">Result</label>
    <button v-on:click="decode">Decode & download</button>
  </div>
</template>

<script>
import MonacoEditor from "@/components/MonacoEditor.vue";

export default {
  components: {
    MonacoEditor
  },
  data() {
    return {
      toolData: {
        data: "",
        base64Mode: "encode",
        stripMime: true
      },
      toolResult: ""
    };
  },
  methods: {
    encode() {
      const file = this.$refs.fileEncodeUpload.files[0];
      const reader = new FileReader();

      reader.onload = () => {
        if (this.toolData.stripMime) {
          this.toolResult = reader.result.split(",")[1];
        } else {
          this.toolResult = reader.result;
        }
      };

      if (file) {
        reader.readAsDataURL(file);
      }
    },
    decode() {
      const byteCharacters = atob(this.toolData.data.split(",")[1] ?? this.toolData.data);
      const byteNumbers = new Array(byteCharacters.length);

      // create file
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }

      const byteArray = new Uint8Array(byteNumbers);
      const blob = new Blob([byteArray], { type: "application/octet-stream" });

      // download
      const link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      link.download = "file";
      link.click();
    }
  }
};
</script>

<style lang="scss">

</style>