<template>
  <q-page class="justify-center">
<q-list padding class="row justify-center">
<q-field
label="Command"
helper="command to execute on server"
>
<q-input inverted color="secondary" v-model="cmd" />
</q-field>
<q-field
label="Payload"
helper="payload/data to send with command"
>
<q-input inverted color="secondary" v-model="payload" />
</q-field>
<q-btn round @click="send" icon="email" />
</q-list>
<q-input rows="5" v-model="response" readonly inverted type="textarea" float-label="Server Response:" />
</q-page>
</template>
<script>

import btc from 'better-try-catch'
import socket from '../plugins/socket.js'

export default {
  data () {
    return {
      cmd: '',
      payload: '',
      response: ''
    }
  },
  methods: {
    async send () {
      let packet = {cmd: this.cmd, payload: this.payload}
      let res = await socket.send(packet)
      if (typeof res === 'string') this.response = res
      else {
        if (this[res.cmd]) this[res.cmd](res.response)
        else this.response = `no action for returned command ${res.cmd}`
      }
    },
    async doit (response) {
      this.response = `response via doit: ${response}`
    }
  },
  async mounted () {
    console.log('mounting')
    this.$q.notify({type: 'info', message: `Client connecting to', ${socket.url}`})
    let [err] = await btc(socket.connect)()
    if (err) { this.$q.notify({type: 'negative', message: 'Websocket Server Not Available'}) } else {
      this.$q.notify({type: 'positive', message: 'Ready'})
      socket.listen()
    }
  }
}

</script>

<style>
</style>
