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

<script>
import Draggable from '../components/Draggable'
import CText from './CText.vue'
import CMarquee from './CMarquee.vue'
import CImage from './CImage.vue'
import CVideo from './CVideo.vue'
import CTime from './CTime.vue'
import CWeather from './CWeather.vue'
import CWeb from './CWeb.vue'
import CLive from './CLive.vue'

export default {
  name: 'Widget',
  components: {
    Draggable,
    CText,
    CMarquee,
    CImage,
    CVideo,
    CTime,
    CWeather,
    CWeb,
    CLive
  },
  props: {
    scale: {
      type: Number,
      default: -1
    },
    node: {
      type: Object,
      default: null
    },
    root: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  computed: {
    widgetType () {
      return this.node.type
    },
    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: {
    handleBlur ({ 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>

<style scoped lang="scss">
</style>
