<template>
  <div class="import-container">
    <!-- <h3>Select a File to Read</h3> -->
    <input type="file" id="fileInput" @change="readFile" /> <br />

    <button @click="parseTotpUri">Parse tokens</button>
    <button @click="saveImportedSecrets">Save tokens</button>
    <div class="token-list">
      <span v-for="token in parsedTokens" :key="token.issuer">
        <p v-for="(value, name) in token" :key="name">{{ name }}: {{ value }}</p>
        <br />
      </span>
      <!-- <span>{{ parsedTokens }}</span> -->
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      apiBaseUrl: "http://localhost:8000",
      message: "hello",
      file: null,
      fileContent: null,
      allTokens: [],
      parsedTokens: [],
    };
  },

  methods: {
    parseFile() {
      var authArr = this.fileContent.split("\r\n");
      authArr.forEach((ele) => {
        if (ele.length > 80) {
          this.allTokens.push(decodeURIComponent(ele));
        }
      });
    },

    readFile(e) {
      const file = e.target.files[0]; // Get the selected file
      if (file) {
        var reader = new FileReader();
        reader.onload = () => {
          this.fileContent = reader.result;
        };
        reader.readAsText(file);
      } else {
        document.getElementById("fileContent").textContent = "No file selected";
      }
    },

    parseTotpUri() {
      this.parseFile();
      this.allTokens.forEach((token) => {
        const url = new URL(token);
        const scheme = url.protocol.slice(0, -1);
        var label = decodeURIComponent(url.pathname.slice(1)); // Remove the leading '/'
        const type = label.slice(1, -1).split("/")[0];
        label = label.slice(6);
        let username, issuerFromLabel;
        const labelParts = label.split(":");
        if (labelParts.length === 2) {
          issuerFromLabel = labelParts[0];
          username = labelParts[1];
        } else {
          username = label;
        }

        const params = {};
        url.searchParams.forEach((value, key) => {
          params[key] = value;
        });

        console.log(params);

        const secret = params.secret;
        const issuer = params.issuer || issuerFromLabel;
        const algorithm = params.algorithm || "SHA1";
        const digits = params.digits || "6";
        const period = params.period || "30";
        const counter = params.counter;

        const parts = {
          scheme,
          type,
          label,
          username,
          issuer,
          secret,
          algorithm,
          digits,
          period,
          counter,
        };

        this.parsedTokens.push(parts);
      });
    },

    async createSecret(formData) {
      const url = `${this.apiBaseUrl}/secret`;
      const token = sessionStorage.getItem("token");
      const bodyData = { data: btoa(JSON.stringify(formData)) };
      const requestOptions = {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(bodyData),
      };
      console.log("this request sent\n", requestOptions);
      await fetch(url, requestOptions)
        .then((response) => response.json())
        .then((data) => console.log(data));
    },

    async saveImportedSecrets() {
      for (var i = 0; i < this.parsedTokens.length; i++) {
        await this.createSecret(this.parsedTokens[i]);
      }
      this.$emit("close", true);
    },
  },
};
</script>

<style scoped>
.import-container {
  /* max-height: 60vh; */
  overflow: hidden;
  margin-top: 1vh;
}

.token-list {
  height: 60vh;
  margin-top: 10px;
  overflow-y: scroll;
}
</style>
