<template>
  <b-card no-body>
    <b-tabs card pills>
      <b-tab title="File Scan" active>
        <b-input-group>
          <b-form-file placeholder="Select or drop files here" v-model="file"/>
          <b-input-group-append>
            <b-button variant="primary" :disabled="!file || uploading" @click="scanFile">Scan</b-button>
          </b-input-group-append>
        </b-input-group>

        <b-progress class="mt-3" v-if="uploading" :value="progress" animated />
      </b-tab>

      <b-tab title="URL Scan">
        <b-input-group>
          <b-input type="url" placeholder="https://secure.eicar.org/eicar.com.txt" v-model="url"/>
          <b-input-group-append>
            <b-button variant="primary" :disabled="!isUrl(url)" @click="scanUrl">Scan</b-button>
          </b-input-group-append>
        </b-input-group>
      </b-tab>
    </b-tabs>
  </b-card>
</template>

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

import ScanResult from '~/models/scan-result';

export default Vue.extend({
  data() {
    return {
      uploading: false,
      progress: 0,

      file: null as File | null,
      url: '' as string,
    }
  },

  methods: {
    isUrl(url: string) : boolean {
      return /(http|https):\/\/(\w+:?\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@\-\/]))?/.test(url);
    },

    async scanFile() {
      if (!this.file || this.uploading)
        return

      const data = new FormData();

      data.append('file', this.file, this.file.name);

      try
      {
        this.uploading = true;

        const result = await this.$axios.$post<ScanResult>('queue/file', data, {
          onUploadProgress: (progressEvent) => {
            if (progressEvent.total == 0)
              return;

            this.progress = progressEvent.loaded / progressEvent.total * 100;
          }
        });

        await this.$router.push({name: 'id', params: {id: result.id}});
      }
      finally {
        this.progress = 0;
        this.uploading = false;
      }
    },

    async scanUrl() {
      if (!this.isUrl(this.url))
        return;

      const data = new FormData();

      data.append('url', this.url);

      const result = await this.$axios.$post<ScanResult>('queue/url', data);

      await this.$router.push({name: 'id', params: {id: result.id}});
    }
  }
});
</script>
