<template>
  <div>
    <div>
      <div class="filter-buttons">
        <el-button-group>
          <el-button
            type="success"
            v-for="band in filterBands"
            :key="band"
            @click="filterTable(band)"
          >
            {{ band }}
          </el-button>
          <el-button type="success" @click="clearFilter" v-if="showClear"
            >Clear</el-button
          >
        </el-button-group>
        <div>
          <el-form-item label="Show OTPs">
            <el-switch v-model="showSecrets" active-value="yes" inactive-value="no" />
          </el-form-item>
        </div>
        <div class="sort-options">
          <span>
            <el-form-item label="Sort">
              <el-select
                v-model="currentSort"
                placeholder="Select"
                style="width: 80px"
                @change="sortItems"
              >
                <el-option
                  v-for="item in sortOptions"
                  :key="item.key"
                  :label="item.name"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
          </span>
        </div>
      </div>
    </div>

    <div id="cards" v-if="loadCards">
      <span v-for="secret in filteredSecretsList" :key="secret.id">
        <SecretCard
          :issuer="secret.issuer"
          :username="secret.username"
          :secret="secret.secret"
          :id="secret.id"
          :showOtp="showSecrets"
          :key="showSecrets"
          @edit="editSecret"
        />
      </span>
    </div>
  </div>
</template>

<script>
import { TOTP } from "totp-generator";

import SecretCard from "./SecretCard.vue";

export default {
  components: { SecretCard },
  data() {
    return {
      message: "Hello List Secret",
      apiBaseUrl: "http://localhost:8000",
      secretsList: [],
      filteredSecretsList: [],
      filterBands: ["A-C", "D-I", "J-O", "P-S", "T-Z"],
      filterBandsVals: {
        "A-C": ["A", "B", "C"],
        "D-I": ["D", "E", "F", "G", "H", "I"],
        "J-O": ["J", "K", "L", "M", "N", "O"],
        "P-S": ["P", "Q", "R", "S"],
        "T-Z": ["T", "U", "V", "W", "X", "Y", "Z"],
      },
      currentFilter: [],
      loadCards: false,
      showClear: false,
      showSecrets: "yes",
      currentSort: "asc",
      sortOptions: [
        {
          name: "A-Z",
          key: "asc",
        },
        {
          name: "Z-A",
          key: "desc",
        },
      ],
    };
  },

  methods: {
    async listSecrets() {
      const url = `${this.apiBaseUrl}/secret`;
      const token = sessionStorage.getItem("token");
      const requestOptions = {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
      };
      console.log(requestOptions);
      const response = await fetch(url, requestOptions)
        .then((response) => response.json())
        .then((data) => {
          // console.log(data);
          return data;
        })
        .catch((err) => console.log(err));

      response.forEach((element) => {
        // console.log(element);
        const row = this.parseSecret(element.data);
        row["id"] = element["id"];
        this.secretsList.push(row);
      });
      this.filteredSecretsList = this.secretsList;
      this.sortItems();
      this.loadCards = true;
    },

    parseSecret(gibberish) {
      const jsonString = atob(gibberish);
      const secret = JSON.parse(jsonString);
      return secret;
    },

    generateTotp(secret) {
      const { otp, expires } = TOTP.generate(secret);
      console.log(expires);
      return otp;
    },

    editSecret(id) {
      const editingSecret = this.secretsList.filter((element) => {
        return element.id === id;
      });
      // console.log(editingSecret);
      this.$emit("edit", editingSecret[0]);
    },

    filterTable(band) {
      const letters = this.filterBandsVals[band];
      this.currentFilter = letters;
      this.showClear = true;
    },

    checkFirstLetter(row) {
      const firstLetter = row.issuer[0].toUpperCase();
      const index = this.currentFilter.indexOf(firstLetter);
      if (index >= 0) {
        return true;
      }
      return false;
    },

    clearFilter() {
      this.filteredSecretsList = this.secretsList;
      this.showClear = false;
    },

    sortItems() {
      if (this.currentSort === "asc") {
        this.filteredSecretsList.sort((a, b) => a.issuer.localeCompare(b.issuer));
      } else if (this.currentSort === "desc") {
        this.filteredSecretsList.sort((a, b) => b.issuer.localeCompare(a.issuer));
      }
    },
  },

  computed: {},

  watch: {
    currentFilter: function () {
      const filteredList = this.secretsList.filter(this.checkFirstLetter);
      this.filteredSecretsList = filteredList;
      this.sortItems();
    },

    currentSort: function () {
      localStorage.setItem("currentSort", this.currentSort);
    },

    showSecrets: function () {
      localStorage.setItem("showSecrets", this.showSecrets);
    },

    secretsList: function () {
      this.currentSort = localStorage.getItem("currentSort");
      this.filteredSecretsList = this.secretsList;
      this.sortItems();
    },
  },

  mounted() {
    this.listSecrets();
    this.showSecrets = localStorage.getItem("showSecrets");
    this.currentSort = localStorage.getItem("currentSort");
  },
};
</script>

<style>
#cards {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-evenly;
  max-width: 96vw;
}

.filter-buttons {
  width: 96vw;
  display: flex;
  margin: 40px 0 20px 0;
  justify-content: space-around;
  flex-wrap: wrap;
}

.sort-options {
  display: flex;
  justify-content: space-between;
  min-width: 80px;
}
</style>
