<template>
  <div>
    <div class="search-container mb-2">
      <input type="text" :value="searchState.filters.query" @input="onQueryInput" class="form-control" placeholder="zoek..." />
      <clear-input v-if="!!searchState.filters.query" :onClear="() => setQuery('')" />
    </div>

    <div class="pb-4 mr-4 d-inline-block">
      <span class="mr-2">Tags</span>
      <select-dropdown-menu placeholder="Alles" :items="tags" :value="searchState.filters.tagFilter" @input="(tags) => setTagFilter(tags)">
        <p class="px-2 mb-0">Er zijn geen tags. <router-link v-if="permissions.canCreate" to="/cms-tags">Tags toevoegen</router-link></p>
      </select-dropdown-menu>
    </div>
    <div class="pb-4 mr-2 d-inline-block">
      <span class="mr-2">Bestandstype</span>
      <dropdown-menu
        :label="assetTypeFilters[searchState.filters.assetTypeFilter]"
        class="d-inline-block position-relative bg-white border rounded"
      >
        <button
          class="px-2 py-2 d-flex align-items-center dropdown-item"
          v-for="(label, index) in assetTypeFilters"
          :disabled="isDisabled(label)"
          :key="index"
          @click="setAssetTypeFilter(+index)"
        >
          {{ label }}
        </button>
      </dropdown-menu>
    </div>
    <button v-if="hasSelectedFilters && allAssetTypeFiltersEnabled" class="btn btn-link inline-block" @click="resetFilters">
      Verwijder filters
    </button>

    <loader>
      <h2 class="h3 mb-3">{{ searchResultsAmount }} <span v-text="searchResultsAmount === 1 ? 'resultaat' : 'resultaten'"></span></h2>

      <ul class="asset-overview">
        <li
          class="asset"
          v-for="asset in allAssets"
          :key="asset.id"
          :class="{ 'asset-overview-item-readonly': isReadOnly(asset), 'asset-overview-item-owner': isOwner(asset) === true }"
        >
          <asset-overview-item :asset="asset" v-model="valueCopy"></asset-overview-item>
        </li>
      </ul>
      <pagination module="assets" />
    </loader>
  </div>
</template>

<style lang="scss" scoped>
.search-container {
  position: relative;
  width: 50%;

  &:hover .icon-cross {
    opacity: 0.5;

    &:hover {
      opacity: 1;
    }
  }

  @media (max-width: 900px) {
    width: 100%;
  }
}

.asset-overview {
  display: flex;
  flex-wrap: wrap;
  padding: 0;
  margin: 1rem -0.5rem 0;
}

.asset {
  display: flex;
  flex: 0 200px;
  list-style: none;
  margin: 0.25rem;
}
</style>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { namespace } from 'vuex-class';
import _debounce from 'lodash/debounce';
import _isEqual from 'lodash/isEqual';
import { ValueSyncMixin } from '../shared/value-sync-mixin.js';

import pagination from '../shared/pagination.vue';
import clearInput from '../shared/clear-input.vue';
import assetOverviewItem from './asset-overview-item.vue';
import selectDropdownMenu from '../shared/select-dropdown-menu.vue';
import loader from '../shared/loader.vue';
import { Asset, AssetTag, AssetTypeFilter } from '../types/api';
import { AssetSearchResult } from '../api/asset-api';
import { PermissionListModel, PermissionTypes } from '../stores/types/PermissionStoreModel';
import { AssetSearchState, INITIAL_SEARCH_STATE } from '../stores/modules/asset-store';

const AssetStore = namespace('assets');
const AssetTagStore = namespace('cmsTag');
const PermissionStore = namespace('permissions');

@Component({
  components: {
    assetOverviewItem,
    loader,
    pagination,
    clearInput,
    selectDropdownMenu
  },
  mixins: [ValueSyncMixin]
})
export default class AssetOverview extends Vue {
  @Prop(String) readonly value!: string | null;
  @Prop({ type: Number, default: AssetTypeFilter.All }) readonly assetTypeFilterKey!: AssetTypeFilter;

  @PermissionStore.Getter('getPermissions') readonly getPermissions!: (itemName: string) => PermissionListModel;
  @AssetStore.State('isLoadingAssets') readonly isLoadingAssets!: boolean;
  @AssetStore.State('allAssets') readonly allAssets!: Asset[];
  @AssetStore.State('result') readonly result!: AssetSearchResult;
  @AssetStore.State('searchState') readonly searchState!: AssetSearchState;
  @AssetStore.Action('fetchItems') readonly fetchItems!: () => Promise<void>;
  @AssetStore.Mutation('setQuery') readonly setQuery!: (query: string) => void;
  @AssetStore.Mutation('setAssetTypeFilter') readonly setAssetTypeFilter!: (filter: AssetTypeFilter) => void;
  @AssetStore.Mutation('setTagFilter') readonly setTagFilter!: (filter: string[]) => void;
  @AssetStore.Mutation('resetFilters') readonly resetFilters!: () => void;
  @AssetTagStore.State('itemsCache') readonly tags!: AssetTag[];
  @AssetTagStore.Action('fetchItems') readonly fetchTags!: () => Promise<void>;

  isReadOnly(item) {
    return PermissionTypes[String(item.userEntityPermission)] === PermissionTypes.Read;
  }

  isOwner(item) {
    return item.userIsOwner;
  }

  isDisabled(label) {
    return this.allAssetTypeFiltersEnabled ? false : label !== this.assetTypeFilters[this.assetTypeFilterKey];
  }

  get allAssetTypeFiltersEnabled() {
    return this.assetTypeFilters[AssetTypeFilter.All] === this.assetTypeFilters[this.assetTypeFilterKey];
  }

  get isLoading() {
    return this.isLoadingAssets;
  }

  get searchResultsAmount() {
    return this.result ? this.result.totalQueryItems : '';
  }

  get assetTypeFilters(): { [key in AssetTypeFilter]: string } {
    return {
      [AssetTypeFilter.All]: 'Alles',
      [AssetTypeFilter.Image]: 'Afbeelding',
      [AssetTypeFilter.PDF]: 'PDF',
      [AssetTypeFilter.Zip]: 'Zip',
      [AssetTypeFilter.Other]: 'Overige'
    };
  }

  get hasSelectedFilters(): boolean {
    return !_isEqual(this.searchState, INITIAL_SEARCH_STATE);
  }

  get permissions(): PermissionListModel {
    return this.getPermissions('CmsAsset');
  }

  created() {
    this.fetchTags();
    this.setAssetTypeFilter(this.assetTypeFilterKey);
    this.onQueryInput = _debounce(this.onQueryInput, 300);
  }

  onQueryInput(e) {
    this.setQuery(e.target.value);
  }

  @Watch('searchState', { deep: true })
  async onSearchStateChange() {
    this.fetchItems();
  }
}
</script>
