<template>
  <div class="instrument-overview">
    <instrument-filter
      class="instrument-overview__filter"
      v-if="$flavor.showInstrumentFilterSidebar"
      @filter="updateFilter"
    />
    <div class="instrument-overview__filter" v-else />
    <div class="instrument-overview__list">
      <router-link
        :to="{ name: 'instrument', params: { slug: instrument.slug } }"
        data-cy="instrument"
        tag="div"
        v-for="instrument in filteredInstruments"
        :key="instrument.id"
      >
        <instrument-entry :instrument="instrument" />
      </router-link>
    </div>
  </div>
</template>

<script>
import InstrumentFilter from '@/components/instruments/InstrumentFilter';
import InstrumentEntry from '@/components/instruments/InstrumentEntry';
import INSTRUMENTS_QUERY from '@/graphql/gql/queries/instrumentsQuery.gql';
import INSTRUMENT_FILTER_QUERY from 'gql/local/instrumentFilter.gql';

export default {
  components: {
    InstrumentFilter,
    InstrumentEntry,
  },

  apollo: {
    instruments: {
      query: INSTRUMENTS_QUERY,
      update(data) {
        return this.$getRidOfEdges(data).instruments;
      },
    },
    instrumentFilter: {
      query: INSTRUMENT_FILTER_QUERY,
      update({ instrumentFilter }) {
        const { currentFilter } = instrumentFilter;
        if (currentFilter && currentFilter.indexOf(':') > -1) {
          const [filterType, identifier] = currentFilter.split(':');
          if (filterType === 'type') {
            this.filter = (i) => i.type.id === identifier;
          } else {
            this.filter = (i) => i.type.category.id === identifier;
          }
        } else {
          this.filter = (i) => i; // identity
        }
        return instrumentFilter;
      },
    },
  },

  data() {
    return {
      instruments: [],
      filter: (i) => i, // identity
      instrumentFilter: {
        currentFilter: '',
      },
    };
  },

  computed: {
    filteredInstruments() {
      return this.instruments.filter((i) => this.filter(i));
    },
  },

  methods: {
    updateFilter(filter) {
      this.filter = filter;
    },
  },
};
</script>

<style scoped lang="scss">
@import '~styles/helpers';

.instrument-overview {
  display: grid;
  //grid-template-rows: auto auto 1fr;
  grid-template-columns: 300px auto;
  grid-column-gap: $small-spacing;
  //@include centered(800px);
  padding: 0 $small-spacing;

  &__filter {
  }

  &__list {
    padding: $large-spacing 0;
    max-width: $screen-width;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-self: center;
  }

  &__list-item {
    padding: $medium-spacing 0;

    @include regular-text;
    @include table-row($color-silver);
  }
}
</style>
