<template>
  <b-overlay :show="actionPending" rounded="sm">
    <b-card
        :title="cardTitle"
        class="m-2"
        v-hotkey.prevent="keymap"
    >
      <b-card-text>
        Could not read device data!
      </b-card-text>

      <b-button @click="bringOnline" variant="success" class="mr-1 mt-1">Bring online</b-button>
      <b-button @click="bringOffline" variant="danger" class="mr-1 mt-1">Bring offline</b-button>
      <b-button @click="doManualAlert" variant="warning" class="mr-1 mt-1">Manual alert</b-button>
    </b-card>
  </b-overlay>
</template>

<script>
export default {
  name: "SingleDeviceBuzgerator",
  props: {
    'device_id': {
      type: String
    }
  },
  data() {
    return {
      actionPending: false
    }
  },
  computed: {
    cardTitle() {
      return `Device: ${this.device_id}`
    },
    keymap() {
      return {
        "up": this.bringOnline,
        "down": this.bringOffline,
        "right": this.doManualAlert
      }
    }
  },
  methods: {
    performPostAndEverything(url) {
      return new Promise((resolve, reject) => {
        this.actionPending = true
        this.$api.post(url).then(() => {
          this.actionPending = false
          resolve()
        }).catch((error) => {

          if (!error.response) {
            // network error happened
            this.$showToast("Some network error happened.\nCheck logs!")
          } else {
            // server returned bruh moment
            this.$showToast(`The server returned error: ${error.response.status} ${error.response.statusText}\n${error.response.data}`)
          }

          this.actionPending = false
          reject()
        })
      })
    },
    bringOffline() {
      this.performPostAndEverything(`/devices/${this.device_id}/offline`).then(()=> {
        this.$showToast("Offline command issued!", "success")
      })
    },
    bringOnline() {
      this.performPostAndEverything(`/devices/${this.device_id}/online`).then(() => {
        this.$showToast("Online command issued!", "success")
      })
    },
    doManualAlert() {
      this.performPostAndEverything(`/devices/${this.device_id}/alert`)
    }
  }
}
</script>

<style scoped>

</style>