import Vue from 'vue'

Vue.directive('scroll-top', {
  componentUpdated: function(el, binding) {
    console.log(1)
    let allowScroll = false
    let goalOffset = 0
    let completeCall = null
    let divisor = 5

    if (typeof binding.value === 'boolean') {
      allowScroll = binding.value
    }
    if (binding.value && typeof binding.value === 'object') {
      allowScroll = binding.value.allowScroll || false
      goalOffset = binding.value.offset || 0
      completeCall = binding.value.complete
      divisor = binding.value.divisor || 5
    }

    const element = el.$el ? el.$el : el

    if (allowScroll === true) {
      if (element.scrollTop === goalOffset) {
        if (completeCall) {
          completeCall()
        }
        return
      }

      let direction = 'up'
      if (goalOffset > element.scrollTop) {
        direction = 'up'
      } else {
        direction = 'down'
      }

      let offsetDiff = Math.abs(goalOffset - element.scrollTop)

      const timer = setInterval(() => {
        const ispeed = Math.ceil(offsetDiff / divisor)

        offsetDiff = offsetDiff - ispeed

        if (direction === 'up') {
          element.scrollTop = element.scrollTop + ispeed
        } else {
          element.scrollTop = element.scrollTop - ispeed
        }

        if (element.scrollTop === goalOffset) {
          clearInterval(timer)
          if (completeCall) {
            completeCall()
          }
        }
      }, 16)
    }
  }
})
