<template>
  <grid-layout
    :layout="layout"
    :responsive-layouts="responsiveLayouts"
    @update:layout="onUpdateLayout"
    class="itf-bento-grid"
    :col-num="4"
    :row-height="200"
    :cols="{ lg: 4, md: 4, sm: 2, xs: 2, xxs: 2 }"
    :preserve-aspect-ratio="true"
    :responsive="true"
    :is-draggable="enabled"
    :is-resizable="false"
    :is-mirrored="false"
    :is-bounded="true"
    :vertical-compact="true"
    :margin="[10, 10]"
    :use-css-transforms="true">
    <grid-item v-for="item in layout"
               drag-allow-from=".itf-bento-card__drag"
               :x="item.x"
               :y="item.y"
               :w="item.w"
               :h="item.h"
               :i="item.i"
               :key="item.i">
      <bento-card :enabled="enabled" @resize="(e) => onResize(item, e)" :w="item.w" :h="item.h">
        <slot name="cell" :item="item" :index="item.i" :component="getComponent(item.i)"></slot>
      </bento-card>
    </grid-item>
  </grid-layout>
</template>
<style lang="scss">
.itf-bento-grid {
  margin: -10px;

  .vue-grid-item.vue-grid-placeholder {
    background-color: #F5F7F9;
    border: 1px solid #F5F7F9;
    opacity: 1 !important;
    border-radius: 10px;
  }
}
</style>
<script>
import { Vue, Prop, Component } from 'vue-property-decorator';
import { GridLayout, GridItem } from 'vue-grid-layout';
import BentoCard from './BentoCard.vue';

export default @Component({
  name: 'itfBentoGrid',
  components: {
    GridLayout,
    GridItem,
    BentoCard
  }
})
class itfBentoGrid extends Vue {
  @Prop() layout;
  @Prop() responsiveLayouts;
  @Prop() components;
  @Prop({ type: Boolean, default: true }) enabled;

  onResize(item, [w, h]) {
    const newLayout = this.layout.map((i) => {
      if (i.i === item.i) {
        i.w = w;
        i.h = h;
      }
      return i;
    });
    this.$emit('update:layout', newLayout);
  }

  getComponent(id) {
    return this.components[id] ?? null;
  }

  onUpdateLayout(layout) {
    this.$emit('update:layout', layout);
  }
}
</script>
