<template>
  <div class="home">
    <b-container v-if="ready">
      <b-row>
        <b-col class="total-title">
          <h2>Total login attempts</h2>
        </b-col>
        <b-col class="total-count">
          <h2>{{ getStat('TotalLoginAttempts') }}</h2>
        </b-col>
      </b-row>
      <b-row>
        <b-col class="total-title">
          <h2>Unique passwords</h2>
        </b-col>
        <b-col class="total-count">
          <h2>{{ getStat('UniquePasswords') }}</h2>
        </b-col>
      </b-row>
      <b-row>
        <b-col class="total-title">
          <h2>Unique usernames</h2>
        </b-col>
        <b-col class="total-count">
          <h2>{{ getStat('UniqueUsernames') }}</h2>
        </b-col>
      </b-row>
      <b-row>
        <b-col class="total-title">
          <h2>Unique IPs</h2>
        </b-col>
        <b-col class="total-count">
          <h2>{{ getStat('UniqueIPs') }}</h2>
        </b-col>
      </b-row>
    </b-container>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import axios from 'axios';

type TotalStatsHeaders =
  | 'UniquePasswords'
  | 'UniqueUsernames'
  | 'UniqueIPs'
  | 'UniqueCountries'
  | 'TotalLoginAttempts';

interface TotalStatsResult {
  name: TotalStatsHeaders;
  count: number;
}

@Component
export default class Home extends Vue {
  totalStats?: TotalStatsResult[];

  ready = false;

  @Watch('totalStats', { immediate: true, deep: true })
  getStat(key: TotalStatsHeaders): string | undefined {
    const result = this.totalStats?.find((elem) => elem.name === key);
    if (result) {
      return Number(result?.count).toLocaleString();
    }
    return undefined;
  }

  updateStats(): void {
    const url = `/api/stats?type=total`;
    axios
      .get<TotalStatsResult[]>(url)
      .then((resp) => {
        this.totalStats = resp.data;
        this.ready = true;
        console.log(this.totalStats);
      })
      .catch((e) => {
        console.log(e);
      });
  }

  mounted(): void {
    this.updateStats();

    setInterval(() => {
      this.updateStats();
    }, 5000);
  }
}
</script>
<style scoped lang="scss">
.home {
  text-align: left;
}
.total-title {
  text-align: right;
}
.total-count {
  text-align: left;
}
</style>