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

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

const topicstrs = [ //TODO everything else
  props.room + '/projectors/' + props.position + 'platno/status',
  props.room + '/projectors/' + props.position + 'platno/status',
]

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

function handleIncomingMQTT(topic: string, msg: string) {
  console.log('Received on', topic, 'with message', msg)
  if (topic.includes('status')) {
    //console.log(topic.split('/'))
    let typ = topic.split('/')[4]
    handlePlatnoStatus(msg)
  }
}

enum firankState {
  UP,
  DOWN,
  MOVING,
  STOPPED
}
const firankStatus = ref(firankState.STOPPED)

function handlePlatnoStatus(msg: string) {
  console.log('handling status')
  //console.log(projStatus)
  let newState: firankState
  switch (msg) {
    case "UP":
      newState = firankState.UP
      break
    case "DOWN":
      newState = firankState.DOWN
      break
    case "MOVING":
      newState = firankState.MOVING
      break
    default:
      newState = firankState.STOPPED
      break
  }
  firankStatus.value = newState
}

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')
}
const publishPrefix = ref(props.room + '/firanki/')


</script>

<template>
    <div style="display: flex; gap: 1rem">

    </div>
    <div style="display:flex; gap: 1rem">
        <div>
            <h4>Firanki</h4>
            
            <button 
          @mousedown="publishMQTTMsg(publishPrefix + 'move', 'MOVE_UP')" 
          @mouseup="publishMQTTMsg(publishPrefix + 'move', 'STOP')" >
          <UpIcon /></button>
          <button 
          @mousedown="publishMQTTMsg(publishPrefix + 'move', 'MOVE_DOWN')" 
          @mouseup="publishMQTTMsg(publishPrefix + 'move', 'STOP')" >
          <DownIcon /></button>
        </div>
    </div>
</template>

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