<template>
  <b-overlay :show="actionPending" rounded="sm">
    <b-card
        title="All devices"
        class="m-2"
    >
      <b-card-text>
        Control all devices
      </b-card-text>

      <b-button @click="allOnline" variant="success" class="mr-1 mt-1">Bring online</b-button>
      <b-button @click="allOffline" variant="danger" class="mr-1 mt-1">Bring offline</b-button>
    </b-card>
  </b-overlay>
</template>

<script>
export default {
  name: "GlobalDeviceBuzgerator",
  data() {
    return {
      actionPending: false
    }
  },
  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()
        })
      })
    },
    allOnline() {
      this.performPostAndEverything("/devices/online").then(() => {
        this.$showToast("Global online command issued", "success")
      })
    },
    allOffline() {
      this.performPostAndEverything("/devices/offline").then(() => {
        this.$showToast("Global offline command issued", "success")
      })
    }
  }
}
</script>

<style scoped>

</style>