<template>
  <div
    class="grid"
  >
    <ViewComponent
      v-for="(item,key) of saved_config.displays"
      :key="key"
      :config="item"
      :data="log(item.source)"
    />
    <ConfigEditor
      v-model="config"
      :template="template"
    />
  </div>
</template>

<script>
import Vuex from 'vuex';
import { copy_object } from '@sapphirecode/utilities';
import default_config from '../default';
import default_template from '../template';
import ViewComponent from './ViewComponent.vue';
import ConfigEditor from './ConfigEditor.vue';

export default {
  components: { ViewComponent, ConfigEditor },
  props:      {
    app: {
      type:     Number,
      required: true
    }
  },
  data () {
    return {
      config:       copy_object (default_config),
      saved_config: copy_object (default_config),
      template:     default_template
    };
  },
  computed: { ...Vuex.mapGetters ({ log: 'log' }) },
  mounted () {
    this.fetch_log ();
    document.body.addEventListener ('keydown', (ev) => {
      if (ev.key === 's' && ev.ctrlKey) {
        this.save_config ();
        ev.preventDefault ();
        return false;
      }
      return true;
    });
  },
  methods: {
    save_config () {
      fetch ('config', {
        method: 'POST',
        body:   JSON.stringify (this.config)
      });
      this.saved_config = copy_object (this.config);
      this.fetch_log ();
    },
    fetch_log () {
      this.get_log ({
        app_id:  this.app,
        sources: this.saved_config.sources
      });
    },
    ...Vuex.mapActions ({ get_log: 'get_log' })
  }
};
</script>

<style scoped>
.grid {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 100%;
  height: 100%;
}
</style>
