<template>
  <draggable
    ref="draggable"
    :scale="scale"
    :top="widgetsTop"
    :left="widgetsLeft"
    :width="widgetsWidth"
    :height="widgetsHeight"
    v-on="$listeners"
    @blur="onBlur"
  >
    <component
      :is="widgetType"
      :node="node"
      editable
    />
  </draggable>
</template>

<script>
import widget from './widget'
import Draggable from '../components/Draggable'

export default {
  name: 'Widget',
  components: {
    Draggable
  },
  mixins: [widget],
  props: {
    scale: {
      type: Number,
      default: -1
    },
    root: {
      type: Object,
      required: true
    }
  },
  computed: {
    widgetsTop () {
      return this.node.top
    },
    widgetsLeft () {
      return this.node.left
    },
    widgetsWidth () {
      return this.node.width
    },
    widgetsHeight () {
      return this.node.height
    },
    disabled () {
      return this.step === -1
    }
  },
  watch: {
    'node.top': 'check',
    'node.left': 'check',
    'node.width': 'check',
    'node.height': 'check'
  },
  methods: {
    onBlur ({ top, left, width, height }) {
      Object.assign(this.node, {
        top: top | 0,
        left: left | 0,
        width: width | 0,
        height: height | 0
      })
      this.$emit('blur')
    },
    check () {
      const { top, left, width, height } = this.node
      const { width: rWidth, height: rHeight } = this.root
      if (top + height > rHeight) {
        this.$nextTick(() => {
          this.node.top = Math.max(0, rHeight - height)
        })
      }
      if (left + width > rWidth) {
        this.$nextTick(() => {
          this.node.left = Math.max(0, rWidth - width)
        })
      }
    }
  }
}
</script>
