<template>
  <div id="app">
    <n :sensors="sensors" />
    <div class="container">
      <div class="row">
        <main role="main" class="col-md-12 ml-sm-auto col-lg-12 pt-3 px-4">
          <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
            <h1 class="h2">Jobs</h1>
          </div>
          <job v-for="(job, id) in jobs" :job="job" :key="job.id"></job>
        </main>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import job from './components/Job';
import navbar from './components/Nav';
import EventWebSocket from './websocket';
import Noty from 'noty';

Noty.overrideDefaults({
  theme: 'bootstrap-v4',
  timeout: 5000
});

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

let ws = new EventWebSocket(window.arm_config.url);

ws.on('notification', function(data) {
  console.log(data);
  new Noty({
    type: data.type || 'alert',
    text: data.message
  }).show();
});

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

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

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:complete', function(job) {
  delete d.jobs[job.id];
  Vue.set(d, 'jobs', d.jobs);
});

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,
    n: navbar,
  },
  data() {
    return d;
  }
}
</script>
