<template>
  <b-table :fields="fields" :items="flattenedData" responsive class="m-0" striped>
    <template #cell(completed)="data">
      <div class="h5 m-0">
        <b-icon-check-circle-fill v-if="data.item.succeeded === true" variant="success"/>
        <b-icon-exclamation-circle-fill v-if="data.item.succeeded === false" variant="danger"/>

        <b-icon-bug-fill v-if="!data.item.completed" animation="spin-pulse"
                         class="rounded-circle bg-primary text-white" scale="0.7"/>
      </div>
    </template>

    <template #cell(duration)="data">
      <b-badge v-if="data.item.completed" variant="primary">{{ data.value }} seconds</b-badge>
      <b-badge v-if="!data.item.completed" variant="secondary">pending</b-badge>
    </template>

    <template #cell(threats)="data">
      <div class="text-success" v-if="data.item.succeeded && !data.item.threats.length">No threats have been detected</div>
      <div class="text-danger" v-if="data.item.succeeded === false">Scan failed to complete due to the error or timeout</div>
      <div v-if="!data.item.completed">Scan is in progress</div>

      <ul v-if="data.item.completed && data.item.threats.length" class="list-inline m-0">
        <li class="text-danger" v-for="threat in data.item.threats" v-bind:key="threat">{{ threat }}</li>
      </ul>
    </template>
  </b-table>
</template>


<script lang="ts">
import Vue from 'vue';

import ScanResult from '~/models/scan-result';
import ScanResultEntryFlattened from '~/models/scan-result-entry-flattened';

export default Vue.extend({
  async asyncData({params, $axios}) {
    return {data: await $axios.$get<ScanResult>(`results/${params.id}`)}
  },

  created() {
    this.timer = setInterval(this.getData, 1000 * 5);
  },

  beforeDestroy() {
    clearInterval(this.timer);
  },

  methods: {
    async getData() {
      this.data = await this.$axios.$get<ScanResult>(`results/${this.$route.params.id}`);
    }
  },

  computed: {
    flattenedData(): ScanResultEntryFlattened[] {
      return Object
          .entries((this.data as ScanResult).results)
          .map(([k, v]) => new ScanResultEntryFlattened(
              k, v.completed, v.succeeded, v.duration, v.threats))
    }
  },

  data() {
    return {
      data: {} as ScanResult,

      fields: [
        {key: 'id', label: 'Backend'},
        {key: 'completed', label: 'Completed'},
        {key: 'duration', label: 'Duration'},
        {key: 'threats', label: 'Threats'},
      ],

      timer: 0 as any // otherwise it conflicts with SSR / Type Checking
    }
  }
});
</script>
