<template>
  <div class="p-grid p-m-2">
    <div class="p-col-12 p-md-3">
      <div class="p-panel p-shadow-3">
        <div class="p-panel-header">Devices</div>
        <div class="p-panel-content">
          <ul>
            <li v-for="(device, id) in devices" :key="id">
              <button
                class="p-button p-button-text"
                @click="selectDevice(id)"
              >
                {{ id }}
              </button>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <div class="p-col-12 p-md-9" v-if="selected">
      <div class="p-panel p-shadow-3">
        <div class="p-panel-header">Properties</div>
        <div class="p-panel-content">
          <PropertyTree :properties="devices[selected].property" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { reactive } from 'vue'
import MQTTService from './services/mqtt.js'
import PropertyTree from './PropertyTree.vue'

export default {
  components: { PropertyTree },
  data() {
    return {
      devices: reactive({}),
      selected: null,
    }
  },
  mounted() {
    this.mqtt = new MQTTService()

    this.mqtt.client.on('connect', () => {
      console.log('Connected to MQTT broker')
      this.mqtt.subscribe('asset/+/status', this.handleStatus)
      this.mqtt.subscribe('asset/+/property/#', this.handleProperty)
    })
  },
  methods: {
    selectDevice(id) {
      this.selected = id
    },

    handleStatus(payload, topic) {
      const deviceId = topic.split('/')[1]
      if (!this.devices[deviceId]) this.devices[deviceId] = { property: {}, status: null }
      this.devices[deviceId].status = payload
    },

    handleProperty(payload, topic) {
      const parts = topic.split('/')
      const deviceId = parts[1]
      const propertyPath = parts.slice(3) // after asset/device/property/...
      if (!this.devices[deviceId]) this.devices[deviceId] = { property: {}, status: null }

      // traverse/create tree
      let node = this.devices[deviceId].property
      propertyPath.forEach((p, i) => {
        if (i === propertyPath.length - 1) {
          // leaf
          node[p] = { value: payload, updated: Date.now() } // flash on update
        } else {
          if (!node[p]) node[p] = {}
          node = node[p]
        }
      })
    },
  },
}
</script>