<template>
  <div>
    <b-row>
      <b-col class="my-2 text-right">
        <b-spinner class="mx-3" style="width: 1.6rem; height: 1.6rem;" variant="secondary"
                   v-if="sampleDownloadPending > 0"/>
        <b-button @click="updateEverything" variant="primary" :disabled="actionPending">Update</b-button>
      </b-col>
    </b-row>
    <b-row>
      <b-col>
        <b-table striped hover :items="samples" :busy="actionPending" :fields="fields">

          <template #cell(probability)="data">
            <span :class="{'text-danger': data.item.probability > 0.51 }" v-if="data.item.probability !== null">
              {{ data.item.probability|round(3) }}
            </span>
            <span v-else class="text-secondary">N/A</span>
          </template>

          <!-- A virtual column -->
          <template #cell(actions)="data">
            <b-button class="mx-1" size="sm" variant="success" @click="playSample(data.item.tag)">
              <b-icon icon="play"/>
            </b-button>
            <b-button class="mx-1" size="sm" variant="primary" :href="getAudioLink(data.item.tag)">
              <b-icon icon="download"/>
            </b-button>
          </template>

          <template #table-busy>
            <div class="text-center my-2">
              <b-spinner class="align-middle mx-2"/>
              <strong>Loading...</strong>
            </div>
          </template>

        </b-table>
      </b-col>
    </b-row>
  </div>
</template>

<script>
import {Howl} from 'howler'
import _ from "lodash"

export default {
  name: "Samples",
  data() {
    return {
      samples: [],
      fields: [
        {
          key: 'tag',
          sortable: false
        },
        {
          key: 'device_id',
          sortable: true
        },
        {
          key: "device_date",
          sortable: true
        },
        {
          key: "probability",
          sortable: true
        },
        "actions"
      ],
      actionPending: false,
      sampleDownloadPending: 0,
      sample: null,
      errorText: null
    }
  },
  methods: {
    playSample(tag) {

      if (this.sample !== null && this.sample.playing()) {
        this.sample.stop()
      }

      this.sampleDownloadPending++

      this.sample = new Howl({
        src: [this.getAudioLink(tag)],
        format: ["wav"],
        loop: false,
        onload: () => {
          this.sampleDownloadPending--
        },
        autoplay: true,
        preload: true,
        onloaderror: (id, err) => {
          this.$showToast(`Howler error: [${id}] ${err}`)
          this.sampleDownloadPending--
        }
      })

    },
    getAudioLink(tag) {
      return process.env.VUE_APP_API_LOCATION + "/object/" + tag
    },
    updateEverything() {
      this.samples = []

      this.actionPending = true
      const sample_promise = this.$api.get("/sample")
      const output_promise = this.$api.get("/output")

      Promise.all([sample_promise, output_promise]).then((prom) => {
        this.samples = []
        const samples = prom[0].data
        const results = prom[1].data

        samples.forEach((sample) => {
          let elm = sample
          const result = _.find(results, (e) => e.tag === sample.tag)

          if (result) {
            elm.probability = result.probability
          } else {
            elm.probability = null
          }

          this.samples.push(elm)
        })


        this.actionPending = false
      })

    }
  },
  filters: {
    round(value, decimals) {
      if (!value) {
        value = 0;
      }

      if (!decimals) {
        decimals = 0;
      }

      value = Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals);
      return value;
    }
  },
  mounted() {
    this.updateEverything()
  }
}
</script>

<style scoped>

</style>