<template>
  <ul :class="[componentClass]">
    <li
      v-for="(item, index) in whereFilteredList"
      :key="index"
      :class="{ 'c-item': true }"
    >
      <div class="c-caption">{{ item.label }}</div>
      <div class="c-value">{{ whereFilteredListValue(item) }}</div>
      <div class="c-btn-remove" v-on:click="onClick(item)"></div>
    </li>
    <li
      class="c-btn-removeall"
      v-show="whereFilteredList.length > 0"
      v-on:click="onClickRemoveAll()"
    >
      {{ this.removeAllButtonLabel }}
    </li>
  </ul>
</template>

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

export default {
  extends: base,
  props: {
    items: {
      type: Array,
      default: null,
      required: true
    },
    refreshDependency: {
      type: Boolean,
      default: true
    },
    removeAllButtonLabel: {
      type: String,
      default: "Wyczyść"
    }
  },
  data: function() {
    return {
      componentClass: "c-filter-presenter"
    };
  },
  computed: {
    whereFilteredList: function() {
      return this.items.filter(
        item =>
          this.where[item.dataFieldIdent] !== null &&
          this.where[item.dataFieldIdent] !== undefined &&
          this.where[item.dataFieldIdent] !== ""
      );
    }
  },
  methods: {
    onClick: function(item) {
      let payload = {
        sourceKind: "where",
        appWindowIdent: this.appWindowIdent,
        dataSet: this.dataSet,
        dataFieldIdent: item.dataFieldIdent,
        dataFieldValue: null
      };
      this.setDataSetFieldValue(payload);
      if (this.refreshDependency) this.refresh();
    },

    onClickRemoveAll: function() {
      this.whereFilteredList.forEach(item => {
        let payload = {
          sourceKind: "where",
          appWindowIdent: this.appWindowIdent,
          dataSet: this.dataSet,
          dataFieldIdent: item.dataFieldIdent,
          dataFieldValue: null
        };
        this.setDataSetFieldValue(payload);
      });
      if (this.refreshDependency) this.refresh();
    },

    whereFilteredListValue: function(item) {
      let values = item.values;
      if (values) {
        return values[this.where[item.dataFieldIdent]];
      } else return this.where[item.dataFieldIdent];
    }
  }
};
</script>