<template>
  <div>
    <slot
      v-bind:views="views"
      v-bind:isCurrentView="isCurrentView"
      v-bind:toggleView="toggleView"
      v-bind:setView="setView"
    ></slot>
  </div>
</template>

<script>
export default {
  props: {
    initial: {
      default: () => {}
    }
  },
  data() {
    return {
      views: this.$props.initial,
      keyListener: e => {
        // Esc
        if (e.keyCode === 27) {
          this.hideAllViews();
        }
      }
    };
  },
  methods: {
    setView(viewId, show) {
      this.$data.views[viewId] = show;
    },
    setViews(updates) {
      this.$data.views = {...this.data.views, updates};
    },
    toggleView(viewId) {
      Object.keys(this.$data.views).forEach(key => {
        if (key !== viewId) {
          this.setView(key, false);
        }
      });

      this.setView(viewId, !this.isCurrentView(viewId));
    },
    isCurrentView(viewId) {
      return this.$data.views[viewId];
    },
    hideAllViews() {
      Object.keys(this.$data.views).forEach(key => {
        this.setView(key, false);
      });
    }
  },
  mounted() {
    window.addEventListener('keydown', this.$data.keyListener);;
  },
  destroyed() {
    window.removeEventListener('keydown', this.$data.keyListener);
  }
}
</script>
