<template>
  <ul
    v-bind:class="[componentClass]"
    tabindex="0"
  >
    <draggable class="draggable">
      <li
        v-bind:class="['c-item', { 'c-active': activeWindowIdent === row.appWindowUniqIdent }]"
        v-for="(row, index) in appWindowsList"
        :key="index"
      >
        <div
          class="c-btn-close"
          tabindex="2"
          v-on:click="deleteAppWindow({ appWindowIdent: row.appWindowUniqIdent })"
        />
        <div
          class="c-window"
          tabindex="0"
          v-on:click="setActiveAppWindow({ appWindowIdent: row.appWindowUniqIdent })"
        >{{ row.appWindowTranslatedDesc }}</div>
        <div
          class="c-btn-reload"
          tabindex="1"
          v-on:click="reloadAppWindow({ appWindowIdent: row.appWindowUniqIdent })"
        />
      </li>
    </draggable>
  </ul>
</template>

<script>
import draggable from 'vuedraggable'
import { mapGetters, mapActions } from "vuex";
export default {
  data: function () {
    return {
      componentClass: "c-manager"
    };
  },
  components: {
    draggable
  },
  props: {
    showMainWindow: {
      type: Boolean,
      default: true,
      required: false
    }
  },
  computed: {
    ...mapGetters('csAppWindowsUtils', ['csAppWindows', 'activeWindowIdent', 'mainAppWindowIdent']),
    appWindowsList: function () {
      function allWindowWithIdent(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 this.showMainWindow ? reject(this.csAppWindows, [...allWindowWithIdent(this.csAppWindows)]) : reject(this.csAppWindows, [this.mainAppWindowIdent, ...allWindowWithIdent(this.csAppWindows)])
    }
  },
  methods: {
    ...mapActions("csAppWindowsUtils", [
      "deleteAppWindow",
      "reloadAppWindow",
      "setActiveAppWindow"
    ])
  }
};
</script>
