<template>
  <div id="app" class="container">
    <div class="row" style="padding-bottom: 10px;">
      <div class="col-sm">
        <h1>Ripper</h1>
      </div>
    </div>
    <status :sensors="sensors"></status>
    <temperatures :temperatures="sensors.temperatures"></temperatures>
    <job v-for="(job, id) in jobs" :job="job" :key="job.id"></job>
  </div>
</template>

<script>
import Vue from 'vue'
import job from './components/Job';
import status from './components/Status';
import temperatures from './components/TempStatus';
import EventWebSocket from './websocket';

let d = {
  jobs: {},
  sensors: {}
};

let ws = new EventWebSocket('ws://192.168.2.85:8080/ws');

ws.on('jobs', function(data) {
  // Create jobs components
  d.jobs = data;
});

ws.on('job:create', function(job) {
  // Create new job component
  Vue.set(d.jobs, job.id, job);
});

ws.on('job:update', function(update) {
  let job = d.jobs[update.job_id];

  for (let k in update) {
    if (k !== 'job_id') {
      job[k] = update[k];
    }
  }
});

ws.on('job:progress', function(progress) {
  // Update component status bar for progress.job_id
  let job = d.jobs[progress.job_id];

  if (!job.progress) {
    job.progress = progress;
  } else {
    for (let k in progress) {
      if (k !== 'job_id') {
        job.progress[k] = progress[k];
      }
    }
  }
});

ws.on('sensors', function(status) {
  d.sensors = status;
});

d.ws = ws;

export default {
  name: 'app',
  components: {
    job: job,
    status: status,
    temperatures: temperatures,
  },
  data() {
    return d;
  }
}
</script>
