<template>
  <div
    id="overseer-scan"
    style="padding: 50px;"
  >
    <router-link :to="`/scan/${$route.params.target}`">
      <h1 style="font-size: 2.5em; margin: 0px; float: left; color: #EAECE9">
        {{ $route.params.target }}
      </h1>
    </router-link>
    <span
      v-if="getRequestedScans[0].status == 'COMPLETE'"
      id="scan-button"
      @click="performScan()"
    >Scan Again</span>

    <div
      v-if="!$route.params.scan_id"
      style="float: right;padding: 13px;"
    >
      <input
        id="hide-errors"
        v-model="hideErrors"
        type="checkbox"
        style="height: 19px; width: 19px;"
      >
      <label
        for="hide-errors"
        style="font-size: 1.3em;"
      > Hide Errors</label>
    </div>

    <div id="results">
      <div
        v-for="(scan, index) in getRequestedScans"
        :key="scan.id"
      >
        <ScanResult
          :scan="scan"
          :error="error"
          :loading="loading"
          style="padding: 20px; margin-top: 25px; border-radius: 5px; box-shadow: 0px 0px 10px black;"
        />

        <div
          v-if="getRequestedScans.length != index + 1"
          ref="compareContainer"
          :style="deriveCompareStyle(scan)"
          class="compare-content"
          @click="toggleCompare(scan)"
        >
          <h4
            v-if="!openCompare.includes(scan)"
            style="margin: 0px; text-align: center;"
          >
            Compare
          </h4>
          <ScanCompare
            v-else
            :new-scan="scan"
            :old-scan="getRequestedScans[index + 1]"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ScanResult from '../components/ScanResult.vue'
import ScanCompare from '../components/ScanCompare.vue'

export default {
    name: 'Scan',
    components: {
        ScanResult,
        ScanCompare,
    },
    data() {
        return {
            error: null,
            loading: false,
            hideErrors: true,
            openCompare: []
        }
    },
    computed: {
        /**
         * Returns requested scans based on filters and URI
         **/
        getRequestedScans() {
            let scanCache = this.$store.state.scan_cache;
            let target = this.$route.params.target;
            let scanID = this.$route.params.scan_id;

            if (!scanCache[target])
                return [{ "status": "LOADING" }]

            let filteredItems;
            if (scanID) {
                filteredItems = scanCache[target]
                    .filter(item => item.id == scanID);
            } else {
                filteredItems = scanCache[target]
                    .filter(item => this.hideErrors ? item.status != 'FAILED' : true)
            }

            return filteredItems.length ? filteredItems : [{ "status": "NO_RESULTS" }];
        }
    },
    mounted(){
        // Acquires scans by requested target from the Vuex store.
        this.$store.dispatch("getScansByTarget", this.$route.params.target);
    },
    methods: {
        /**
         * Determines whether a comparison is expanded, and returns the
         * appropriate style.
         **/
        deriveCompareStyle(scan) {
            if (!this.openCompare.includes(scan))
                return {};
            return {
                "width": "90%",
                "padding": "10px",
                "max-height": "10000px",
            }
        },
        /**
         * Updates component variable to expand or collapse a specified
         * scan comparison.
         **/
        toggleCompare(scan) {
            if (this.openCompare.includes(scan))
                this.openCompare = this.openCompare
                    .filter(item => item !== scan)
            else
                this.openCompare.push(scan);
        },
        /**
         * Initiates a new scan for the currently displayed target and
         * navigates to the history view of said target.
         **/
        performScan() {
            this.error = null;
            this.loading = true;
            this.$store.dispatch("performScan", this.$route.params.target)
                .then(scan => {
                    if (scan.error)
                        throw new Error(scan.error)
                    this.$router.push({ path: `/scan/${this.$route.params.target}` })

                    // If you want to navigate to the specific scan
                    // this.$router.push({ path: `/scan/${this.$route.params.target}/${scan.id}` })
                }).catch(err => {
                    this.error = err;
                }).finally(() => {
                    this.loading = false;
                });
        },
    }
}
</script>

<style scoped>
#overseer-scan {
    text-align: left;
}

#results {
    width: 700px;
    margin: 150px auto 0px auto;
}

#scan-button {
    font-size: 1em;
    background-color: #0E6A0E;
    padding: 8px;
    border-radius: 10px;
    float: right;
    font-weight: 700;
    cursor: pointer;
    margin: 8px;
}

.compare-content {
    width: 70px;
    max-height: 22px;
    padding: 0px 10px;
    background-color: #C9582C;
    border-radius: 15px;
    transition: 0.5s;
    font-weight: 700;
    margin: 25px auto 0px auto;
    overflow: hidden;
    cursor: pointer;
}
</style>
