<script setup lang="ts">
//import HelloWorld from './components/HelloWorld.vue'
//import TheWelcome from './components/TheWelcome.vue'
import { ref, onMounted, reactive, watch } from 'vue'
import { $mqtt } from 'vue-paho-mqtt'

const props = defineProps({
  room: String,
})

const topicstrs = [ //TODO everything else
  props.room + '/power/audio/status',
]

const subscriptions =
  topicstrs.map(topic => {
    // console.log('subbing to', topic)
    $mqtt.subscribe(topic, (msg) => {
      // console.log('received:', topic, msg)
      handleIncomingMQTT(topic, msg)
    })
  })


const audioStatus = ref(false)

function handleIncomingMQTT(topic: string, msg: string) {
  console.log('Received on', topic, 'with message', msg)
  audioStatus.value = msg == '1'
}

onMounted(() => {
  // console.log('test')
  //$mqtt.publish('peepee', 'poopoo', 'Qr') // dela

})

function publishMQTTMsg(topic: string, msg: string) {
  //msg = msg.toString()
  console.log('Sending to [', topic, '] with message [', msg, ']')
  $mqtt.publish(topic, msg, 'Qr') //todo refactor to 1 or 0 maybe
  console.log('sent')
}

async function setAudio() {
    let topicPref = props.room + "/power/audio/set"
    let command = '0'
    if (!audioStatus.value) {
        command = '1'
    }
    publishMQTTMsg(topicPref, command)
    //audioStatus.value = command == '1'
}



//TODO organize better, binds, etc.


const roomState = ref(0)
// OFF -> 0; ON -> 1; IN BETWEEN -> 2


</script>

<template>
  <div>
    <!-- TODO lepš -->
    <div>
        <h3>Ozvočenje</h3>
        <button style="" @click="setAudio()">
        {{ audioStatus ? 'UGASNI' : 'PRIŽGI' }}
      </button>
    </div>
  </div>
</template>

<style scoped>
.disabled {
  opacity: .8;
  pointer-events: none;
}
button {
  padding: 1rem;
  width: 100%;
}
</style>
