<template>
  <div :class="[componentClass]">
    <button
      v-if="isBtnRendered"
      :class="['c-btn-back', {'c-inactive':isBtnBackInactive }]" 
      v-on:click="onBtnBackClick"
    />
    <slot name="panelContent"></slot>
    <button
      v-if="isBtnRendered"
      :class="['c-btn-fwd', {'c-inactive':isBtnForwardInactive }]" 
      v-on:click="onBtnForwardClick"
    />
  </div>
</template>

<script>
import base from "./c-base";

export default {
  extends: base,
  data: function() {
    return {
      componentClass: "c-scroll-panel",
      isBtnBackInactive: true,
      isBtnForwardInactive: true
    };
  },
  props: {
    scrollableElement: {
      type: String,
      default: "panel"//allowowed values: panel, panelContent
    },
    scrollValue: {
      type: String,
      default: null
    },
    hideWhenRowsCountLower: {
      type: Number,
      default: -1
    }
  },
  computed: {
    scrollableElm: function() {
      if (this.scrollableElement == "panel") {
        return this.$el;
      } else if (this.scrollableElement == "panelContent") {
        return this.$slots["panelContent"] != null &&
          this.$slots["panelContent"][0] != null
          ? this.$slots["panelContent"][0].elm
          : null;
      } else {
        return this.$el;
      }
    },
    isBtnRendered: function() {
      return (
        this.state === 1
        && !this.rowsIsEmpty
        && (this.rowsCount > 0 ? this.rowsCount : this.dataSet.rows.length) >= this.hideWhenRowsCountLower
      )
    }
  },
  methods: {
    onBtnBackClick: function() {
      if (this.scrollableElm == null) return;

      if (this.scrollableElm.scrollLeft > 0) {
        let scrollValue = (this.scrollValue != null) ? parseFloat(this.scrollValue) : this.$el.scrollWidth
        this.scrollableElm.scrollLeft -= scrollValue
      }
    },
    onBtnForwardClick: function() {
      if (this.scrollableElm == null) return;
      if (this.scrollableElm.scrollLeft < this.scrollableElm.scrollWidth) {
        let scrollValue = (this.scrollValue != null) ? parseFloat(this.scrollValue) : this.$el.scrollWidth
        this.scrollableElm.scrollLeft += scrollValue
      }
    },
    onScroll: function() {
      if(this.scrollableElm == null) return
      this.isBtnBackInactive = this.scrollableElm.scrollLeft === 0
      this.isBtnForwardInactive = (this.scrollableElm.scrollLeft + this.scrollableElm.offsetWidth) === this.scrollableElm.scrollWidth
    }
  },
  mounted: function() {
    if(this.scrollableElm != null) {
      this.scrollableElm.addEventListener('scroll', this.onScroll)
      this.onScroll()
    }
  },
  beforeDestroy: function() {
    if(this.scrollableElm != null) {
      this.scrollableElm.removeEventListener('scroll', this.onScroll)
    }
  }
};
</script>