<template>
  <ul
    v-bind:class="[componentClass]"
    tabindex="-1"
  >
    <button
      v-if="showTabMoveButtons"
      :class="[
        'c-btn-rev',
        btnTabsMoveLeftClass
      ]"
      tabindex="-1"
      @click="tabsScrollLeft"
    ></button>
    <button
      v-if="showTabMoveButtons"
      :class="[
        'c-btn-fwd',
        btnTabsMoveRightClass
      ]"
      tabindex="-1"
      @click="tabsScrollRight"
    ></button>
    <draggable class="c-items" ref="itemsScrollableContainer">
      <li
        :class="[
          'c-item',
          { 'c-active': activeWindowIdent === row.appWindowUniqIdent }
        ]"
        v-for="(row, index) in appWindowsList"
        :key="index"
        v-on:click="setActiveAppWindow({ appWindowIdent: row.appWindowUniqIdent })"
      >
        <button
          class="c-btn-close"
          tabindex="-1"
          v-on:click.stop="deleteAppWindow({ appWindowIdent: row.appWindowUniqIdent })"
        ></button>
        <button
          class="c-btn-reload"
          tabindex="-1"
          v-on:click.stop="onBtnReloadClick({ appWindow: row })"
        ></button>
        {{ row.appWindowTranslatedDesc }}
      </li>
    </draggable>
  </ul>
</template>

<script>
import draggable from 'vuedraggable'
import { mapGetters, mapActions } from "vuex";
export default {
  data: function () {
    return {
      componentClass: "c-manager",
      scrollOffset: 200,
      btnTabsMoveLeftClass: null,
      btnTabsMoveRightClass: null,
      itemsScrollableContainer: null,
      appWindowIdentReload: null,
      appWindowUniqIdentReload: null
    };
  },
  components: {
    draggable
  },
  props: {
    showTabMoveButtons: {
      type: Boolean,
      default: true,
      required: false
    }
  },
  computed: {
    ...mapGetters('csAppWindowsUtils', ['csAppWindows', 'activeWindowIdent', 'mainAppWindowIdent']),
    appWindowsList: function () {
      function allWindowsWithIdent(csAppWindows) {
        return Object.keys(csAppWindows).filter(appWindowIdent => {
          let result = false
          if (csAppWindows[appWindowIdent].appWindowUniqIdent === csAppWindows[appWindowIdent].appWindowIdent) {
            Object.keys(csAppWindows[appWindowIdent].dataSets).forEach(dataSetIdent => {
                csAppWindows[appWindowIdent].dataSets[dataSetIdent].whereFieldsIdents?.forEach(whereField => {
                  if (whereField.isIdent) result = true
                })
            })
          }
          return result
        })
      }
      function reject(obj, keys) {
        return Object.keys(obj)
          .filter(k => !keys.includes(k) && obj[k].showOnMainTabList)
          .map(k => Object.assign({}, {[k]: obj[k]}))
          .reduce((res, o) => Object.assign(res, o), {});
      }
      return reject(this.csAppWindows, [this.mainAppWindowIdent, ...allWindowsWithIdent(this.csAppWindows)])
    }
  },
  methods: {
    ...mapActions("csAppWindowsUtils", [
      "deleteAppWindow",
      "reloadAppWindow",
      "setActiveAppWindow"
    ]),
    tabsScrollLeft: function() {
      let scrollLeftVal

      if(this.itemsScrollableContainer != null && this.itemsScrollableContainer.scrollLeft > 0) {
        if(this.itemsScrollableContainer.scrollLeft > this.scrollOffset) {
          scrollLeftVal = this.itemsScrollableContainer.scrollLeft - this.scrollOffset
          this.itemsScrollableContainer.scroll({left: scrollLeftVal, behavior: 'smooth' })
        } else {
          scrollLeftVal = 0
          this.itemsScrollableContainer.scroll({left: scrollLeftVal, behavior: 'smooth' })
        }
        this.setTabMoveButtons(scrollLeftVal)
      }
    },
    tabsScrollRight: function() {
      let scrollLeftVal
      if(this.itemsScrollableContainer != null && this.itemsScrollableContainer.scrollLeft + this.itemsScrollableContainer.offsetWidth < this.itemsScrollableContainer.scrollWidth) {
        if(this.itemsScrollableContainer.scrollLeft + this.itemsScrollableContainer.offsetWidth + this.scrollOffset < this.itemsScrollableContainer.scrollWidth) {
          scrollLeftVal = this.itemsScrollableContainer.scrollLeft + this.scrollOffset
          this.itemsScrollableContainer.scroll({left: scrollLeftVal, behavior: 'smooth' })
        } else {
          scrollLeftVal = this.itemsScrollableContainer.scrollWidth - this.itemsScrollableContainer.offsetWidth
          this.itemsScrollableContainer.scroll({left: scrollLeftVal, behavior: 'smooth' })
        }
        this.setTabMoveButtons(scrollLeftVal)
      }
    },
    tabsScrollToEnd: function() {
      let scrollLeftVal = this.itemsScrollableContainer.scrollWidth - this.itemsScrollableContainer.offsetWidth
      this.itemsScrollableContainer.scroll({left: scrollLeftVal, behavior: 'smooth' })
      this.setTabMoveButtons(scrollLeftVal)
    },
    onTabAdd: function() {
      if(this.itemsScrollableContainer.offsetWidth < this.itemsScrollableContainer.scrollWidth) {
        this.tabsScrollToEnd()
      }
    },
    onTabRemove: function() {
      this.setTabMoveButtons()
    },
    setTabMoveButtons: function(scrollLeftVal) {
      let scrollLeft = scrollLeftVal == null ? this.itemsScrollableContainer.scrollLeft : scrollLeftVal
      let buttonsActiveClass = 'c-act'

      if(this.itemsScrollableContainer.offsetWidth < this.itemsScrollableContainer.scrollWidth) {
        if(scrollLeft == 0) {
          this.btnTabsMoveLeftClass = null
        } else if(scrollLeft > 0) {
          this.btnTabsMoveLeftClass = buttonsActiveClass
        }
        //
        if(this.itemsScrollableContainer.offsetWidth + scrollLeft < this.itemsScrollableContainer.scrollWidth) {
          this.btnTabsMoveRightClass = buttonsActiveClass
        } else if(this.itemsScrollableContainer.offsetWidth + scrollLeft == this.itemsScrollableContainer.scrollWidth) {
          this.btnTabsMoveRightClass = null
        }
      } else {
        this.btnTabsMoveLeftClass = null
        this.btnTabsMoveRightClass = null
      }
    },
    onBtnReloadClick: function(payload) {
      let appWindow = payload.appWindow
      this.appWindowUniqIdentReload = appWindow.appWindowUniqIdent
      //
      this.reloadAppWindow({
        appWindowIdent: appWindow.appWindowIdent,
        appWindowUniqIdent: appWindow.appWindowUniqIdent,
        query: appWindow.query
      })
    }
  },
  mounted() {
    if(this.showTabMoveButtons == false) return
    this.itemsScrollableContainer = this.$refs.itemsScrollableContainer?.$el
  },
  watch:{
    appWindowsList: function(val, oldval){
      let oldvalKeys = Object.keys(oldval)
      let valKeys = Object.keys(val)

      if(valKeys.length > oldvalKeys.length) {
        if(this.appWindowUniqIdentReload != null) {
          let appWindowIdentAdded = valKeys.filter(i => oldvalKeys.includes(i) == false)[0]
          if(this.appWindowUniqIdentReload == appWindowIdentAdded) {
            this.appWindowUniqIdentReload = null
          }
        }
        //
        if(this.showTabMoveButtons) {
          this.$nextTick(() => {
            this.onTabAdd()
          })
        }
      } else if(valKeys.length < oldvalKeys.length) {
        let appWindowIdentDeleted = oldvalKeys.filter(i => valKeys.includes(i) == false)[0]
        let activeWindowIdent = this.activeWindowIdent
        //
        if(appWindowIdentDeleted != null && appWindowIdentDeleted == this.appWindowUniqIdentReload) {
          return
        }
        //
        if(appWindowIdentDeleted != null && activeWindowIdent == null) {
          let newActiveAppWindowIdent
          if(oldvalKeys.indexOf(appWindowIdentDeleted) == oldvalKeys.length - 1) {
            newActiveAppWindowIdent = valKeys[valKeys.length - 1]
          } else {
            newActiveAppWindowIdent = valKeys[oldvalKeys.indexOf(appWindowIdentDeleted)]
          }
          this.setActiveAppWindow({ appWindowIdent: newActiveAppWindowIdent })
        }
        //
        if(this.showTabMoveButtons) {
          this.$nextTick(() => {
            this.onTabRemove()
          })
        }
      }
    },
  }
};
</script>