<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">
      <FilterBar>
      </FilterBar>
      <router-link
        :to="{ name: 'instrument', params: { slug: instrument.slug } }"
        data-cy="instrument"
        v-for="instrument in filteredInstruments"
        :key="instrument.id"
      >
        <instrument-entry :instrument="instrument" />
      </router-link>
    </div>
  </div>
</template>

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

export default {
  components: {
    FilterBar,
    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;
  @include desktop {
    grid-template-columns: 300px auto;
  }
  grid-column-gap: $small-spacing;

  padding: 0 $small-spacing;

  box-sizing: border-box;

  &__list {
    padding: $large-spacing 0;
    max-width: min($screen-width, 100vw);
    width: 100%;
    display: flex;
    overflow: hidden;
    flex-direction: column;
    justify-self: center;
  }

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

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