<template>
  <div :class="[pickerMode ? 'small' : '', 'list-view']">
    <plugin-header v-if="!pickerMode">
      <template v-slot:title>
        PYXIS
      </template>
    </plugin-header>
    <div
      ref="actions-container"
      class="actions-container"
    >
      <div class="column left">
        <ui-textbox
          v-model="search"
          name="search"
          type="text"
          floating-label
          class="search-pyxis"
          label="Search"
          help="Tip: Use double quotes for exact phrase matches."
          icon-position="right"
          icon="search"
        >
          <template v-slot:icon>
            <ui-icon-button
              icon="search"
              type="secondary"
              @click="debounceSearch(false)"
            />
          </template>
        </ui-textbox>
        <div class="filter-buttons">
          <template v-for="group in buttonsTags">
            <template v-for="option in group.values">
              <ui-button
                :key="option"
                class="filter-button"
                :class="{ active: (buttonsSelectedTags || []).indexOf(option) >= 0 }"
                button-type="button"
                type="secondary"
                @click="handleFilterButtonClick(option)"
              >
                {{ option }}
              </ui-button>
            </template>
          </template>
        </div>
        <div class="search-filters">
          <ui-button
            class="filter-button"
            :class="{ active: lastUpload }"
            button-type="button"
            type="secondary"
            @click="handleLastUploadState"
          >
            Last Upload
          </ui-button>
          <ui-button
            class="filter-button"
            :class="{ active: uploadedYesterday }"
            button-type="button"
            type="secondary"
            @click="toggleUploadedYesterday"
          >
            Uploaded Yesterday
          </ui-button>
          <div class="datepicker-container">
            <ui-datepicker
              floating-label
              placeholder="Select a date"
              :custom-formatter="customFormatDate"
              :disable="uploadedYesterday"
              :max-date="endDate | formatDate"
              :value="startDate | formatDate"
              @input="setStartDate"
            >
              Start Date
            </ui-datepicker>
            <ui-datepicker
              floating-label
              placeholder="Select a date"
              :custom-formatter="customFormatDate"
              :disable="uploadedYesterday"
              :min-date="startDate | formatDate"
              :value="endDate | formatDate"
              @input="setEndDate"
            >
              End Date
            </ui-datepicker>
          </div>
        </div>
        <div class="tags-filters">
          <div class="filter">
            <users-filter
              :username-filter="usernameFilter"
              :users="users"
              @handleAllUsers="handleAllUsers"
              @setOffset="setOffset"
              @setUsernameFilter="setUsernameFilter"
            />
          </div>
          <div class="filter">
            <collection-slug
              :value="collectionSlug"
              @saveCollection="handleCollectionSelection"
            />
          </div>
          <div class="filter">
            <tags
              :provided-tags="checkboxTags"
              :selected-tags="checkboxSelectedTags"
              @selectTags="saveTags"
            />
          </div>
        </div>
      </div>
      <div class="column right">
        <slot />
      </div>
    </div>
    <div class="list-filters">
      <div class="sort-controls">
        <span class="controls-title">Sort:</span>
        <ui-button
          class="sort-action"
          :class="{ active: createdSortStatus }"
          :icon="createdSortDirection | sortIcon"
          button-type="button"
          @click="setSort(SORT_KEYS.CREATED)"
        >
          Created
        </ui-button>
        <ui-button
          class="sort-action"
          :class="{ active: modifiedSortStatus }"
          :icon="modifiedSortDirection | sortIcon"
          button-type="button"
          @click="setSort(SORT_KEYS.MODIFIED)"
        >
          Modified
        </ui-button>
        <ui-button
          class="sort-action"
          :class="{ active: alphabeticalSortStatus }"
          :icon="alphabeticalDirection | sortIcon"
          button-type="button"
          @click="setSort(SORT_KEYS.REFERENCE_NAME)"
        >
          Alphabetical
        </ui-button>
        <ui-button
          class="sort-action"
          :class="{ active: relevanceSortStatus }"
          :icon="relevanceDirection | sortIcon"
          button-type="button"
          @click="setSort(SORT_KEYS.RELEVANCE)"
        >
          Relevance
        </ui-button>
      </div>
      <div class="view-controls">
        <span class="controls-title control-view">View:</span>
        <button
          v-for="item in itemsPerPageOptions"
          :key="`search-size-${item}`"
          :disabled="lastUpload"
          class="search-size"
          :class="{
            active: item === itemsPerPage,
            clickable: !lastUpload
          }"
          type="button"
          @click="setItemsPerPage(item)"
        >
          {{ item }}
        </button>
      </div>
    </div>
    <div class="edit-controls">
      <div
        v-if="!pickerMode"
        class="select-options"
      >
        <ui-button
          :disabled="selectedKeys.length === itemsPerPage"
          button-type="button"
          class="selection-btn"
          type="primary"
          disable-ripple
          @click="$emit('selectAll')"
        >
          Select all
        </ui-button>
        <ui-button
          :disabled="selectedKeys.length <= 1"
          button-type="button"
          class="deselection-btn"
          type="primary"
          disable-ripple
          @click="$emit('deselectAll')"
        >
          Deselect all
        </ui-button>
      </div>
      <transition name="fade">
        <div
          v-if="hasAnyFilter"
          class="results-info"
        >
          <div class="count-info default-title">
            Results: {{ total }}
          </div>
        </div>
      </transition>
      <div
        v-if="!pickerMode"
        class="edit-options"
      >
        <a
          :class="editImagesState"
          @click.prevent="!editImagesState && $emit('openSelection')"
        >
          <ui-icon icon="open_in_new" />Edit Image(s)
        </a>
        <a
          :class="`metadata-modal ${editMetadataState}`"
          @click.prevent="!editMetadataState && $emit('openMetadataModal')"
        >
          <ui-icon icon="open_in_new" />Edit Shared Metadata
        </a>
      </div>
    </div>
    <ul class="results">
      <Result
        v-for="asset in assets"
        :key="asset.id"
        :classes="pickerMode ? 'picker-mode' : ''"
        :date="asset.modifiedDate"
        :name="asset.referenceName || ''"
        :selected="!!selected[asset.id]"
        :src="getCropUrl(asset.asset.path, getCropUrlConf(asset))"
        :path="getCropUrl(asset.asset.path, { referenceName: asset.referenceName || '' })"
        @click="$emit('itemSelect', asset)"
        @dblclick="$emit('itemClick', asset)"
      />
    </ul>
    <Pagination
      v-if="total > itemsPerPage && !lastUpload"
      :offset="offset"
      :limit="itemsPerPage"
      :total="total"
      :picker-mode="pickerMode"
      @setOffset="handlePaginationClick"
    />
  </div>
</template>
<script>

import subDays from 'date-fns/sub_days';
import startOfDay from 'date-fns/start_of_day';
import endOfDay from 'date-fns/end_of_day';
import subMinutes from 'date-fns/sub_minutes';
import _get from 'lodash/get';
import _debounce from 'lodash/debounce';
import { getCropUrl, getIdFromPath } from 'Helpers/asset';
import { parseUrlParameters } from 'Helpers/string';
import Header from 'Components/layout/Header.vue';
import CollectionSlug from 'Components/metadata/CollectionSlug.vue';
import Tags from 'Components/metadata/Tags.vue';
import { decodeArray, getNonDefaultParams, getStateUrlParameters, hasStatusError } from 'Helpers/api';
import {
  ITEMS_PER_PAGE_OPTIONS,
  USERNAME
} from 'Config';
import {
  ASC,
  DEBOUNCE_TIME,
  DEFAULT_THUMBNAIL_RENDITION,
  DESC,
  SORT_KEYS,
  ALL_USERS,
  allUsersOption
} from 'Config/constants';
import { search, getUserByUsername } from 'Api';
import Result from './Result.vue';
import Pagination from './Pagination.vue';
import UsersFilter from './UsersFilter.vue';

const ASSET_WIDTH = 220,
  MINUTES_TO_SUBSTRACT = 10,
  DEFAULT_SORT_CONF = {
    direction: DESC,
    value: SORT_KEYS.MODIFIED
  },
  TAGS_DISPLAYS = {
    BUTTONS: 'buttons',
    CHECKBOX: 'checkbox'
  },
  {
    UiTextbox,
    UiButton,
    UiIcon,
    UiIconButton,
    UiDatepicker
  } = window.kiln.utils.components;

export default {
  filters: {
    sortIcon(sortDirection = '') {
      if (!sortDirection) {
        return '';
      }

      return sortDirection === DESC ? 'arrow_downward' : 'arrow_upward';
    },
    formatDate(rawDate = '') {
      return !rawDate ? null : new Date(rawDate);
    }
  },
  components: {
    UiButton,
    'ui-datepicker': UiDatepicker,
    'ui-textbox': UiTextbox,
    'plugin-header': Header,
    Pagination,
    Result,
    CollectionSlug,
    Tags,
    UiIcon,
    UiIconButton,
    UsersFilter
  },
  props: {
    assetsId: {
      type: String,
      default: ''
    },
    filteredList: {
      type: String,
      default: ''
    },
    assets: {
      type: Array,
      default: () => []
    },
    thumbnailRendition: {
      type: String,
      default: DEFAULT_THUMBNAIL_RENDITION
    },
    itemsPerPage: {
      type: Number,
      default: ITEMS_PER_PAGE_OPTIONS[0]
    },
    itemsPerPageOptions: {
      type: Array,
      default: () => []
    },
    lastUpload: {
      type: Boolean
    },
    total: {
      type: Number,
      default: 0
    },
    tags: {
      type: Object,
      default: () => ({})
    },
    initialValue: {
      type: String,
      default: ''
    },
    itemClick: {
      type: Function,
      default: () => ({})
    },
    initialSearch: {
      type: String,
      default: ''
    },
    initialFilters: {
      type: Object,
      default: () => ({})
    },
    // IDs of selected results in a multi-select context
    selected: {
      type: Object,
      default: () => ({})
    },
    forceRefresh: {
      type: Boolean,
      default: false
    },
    pickerMode: {
      type: Boolean,
      default: false
    },
    uploadingFiles: {
      type: Boolean,
      default: false
    },
    users: {
      type: Array,
      default: () => []
    },
    resetDatesFlag: {
      type: Boolean,
      default: false
    },
    resetFiltersOnUpload: {
      type: Boolean,
      default: false
    },
    siteFilter: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      offset: 0,
      collectionSlug: '',
      search: this.initialSearch,
      error: null,
      sort: DEFAULT_SORT_CONF,
      startDate: null,
      endDate: null,
      uploadedYesterday: false,
      usernameFilter: this.pickerMode ? { username: '', name: '' } : USERNAME,
      SORT_KEYS,
      paginationClicked: false,
      buttonsSelectedTags: [],
      checkboxSelectedTags: [],
      settingFilters: false
    };
  },
  computed: {
    hasInitialValue() {
      return !!this.initialValue;
    },
    buttonsTagsValues() {
      return Object.values(this.buttonsTags)
        .reduce((accum, { values }) => [...values, ...accum], []);
    },
    buttonsTags() {
      return Object.entries(this.tags)
        .reduce((accum, [tagKey, value]) => {
          if (value.display === TAGS_DISPLAYS.BUTTONS) accum[tagKey] = value;

          return accum;
        }, {});
    },
    checkboxButtonsMatchingTags() {
      return this.buttonsTagsValues.filter(item => this.checkboxTagsValues.includes(item));
    },
    checkboxTagsValues() {
      return Object.values(this.checkboxTags)
        .reduce((accum, { values }) => [...values, ...accum], []);
    },
    checkboxTags() {
      return Object.entries(this.tags)
        .reduce((accum, [tagKey, value]) => {
          if (value.display === TAGS_DISPLAYS.CHECKBOX) accum[tagKey] = value;

          return accum;
        }, {});
    },
    allSelectedTags() {
      return [...new Set([...this.buttonsSelectedTags, ...this.checkboxSelectedTags])];
    },
    alphabeticalSortStatus() {
      return this.getSortStatus(SORT_KEYS.REFERENCE_NAME);
    },
    createdSortStatus() {
      return this.getSortStatus(SORT_KEYS.CREATED);
    },
    modifiedSortStatus() {
      return this.getSortStatus(SORT_KEYS.MODIFIED);
    },
    relevanceSortStatus() {
      return this.getSortStatus(SORT_KEYS.RELEVANCE);
    },
    alphabeticalDirection() {
      return this.getSortDirection(SORT_KEYS.REFERENCE_NAME);
    },
    createdSortDirection() {
      return this.getSortDirection(SORT_KEYS.CREATED);
    },
    modifiedSortDirection() {
      return this.getSortDirection(SORT_KEYS.MODIFIED);
    },
    relevanceDirection() {
      return this.getSortDirection(SORT_KEYS.RELEVANCE);
    },
    hasAnyFilter() {
      return !!this.startDate || !!this.endDate || !!this.collectionSlug
        || !!this.search || !!this.allSelectedTags.length || !!this.lastUpload;
    },
    selectedKeys() {
      return Object.keys(this.selected);
    },
    editImagesState() {
      return this.selectedKeys.length < 1 ? 'disabled' : '';
    },
    editMetadataState() {
      return this.selectedKeys.length <= 1 ? 'disabled' : '';
    }
  },
  watch: {
    search() {
      this.debounceSearch(true);
    },
    tags() {
      if (!this.assetsId) {
        // refresh view initially and when the hash updates
        this.urlFiltersSetup().then(() => this.refresh());
      }
    },
    itemsPerPage(newVal, oldVal) {
      if (newVal !== oldVal && !this.uploadingFiles && !this.settingFilters) {
        this.refresh();
      }
    },
    resetDatesFlag() {
      this.startDate = null;
      this.endDate = null;
      this.refresh();
    },
    forceRefresh(newVal) {
      if (newVal) {
        this.refresh();
      }
    },
    uploadingFiles(filesAreUploading) {
      if (!filesAreUploading) {
        this.resetFilters();
        this.endDate = Date.now();
        this.startDate = subMinutes(this.endDate, MINUTES_TO_SUBSTRACT).getTime();
        this.usernameFilter = USERNAME;
        this.$emit('setLastUpload', true);
      }
    },
    resetFiltersOnUpload() {
      this.resetFilters();
      this.usernameFilter = USERNAME;
      this.refresh();
    },
    initialFilters(filters = {}) {
      if (Object.keys(filters).length) {
        const { collectionSlug, tags } = filters;

        // if no collectionSlug nor tags, nothing to do
        if (!collectionSlug && !(tags && tags.length)) return;

        this.collectionSlug = collectionSlug || this.collectionSlug;

        if (tags && tags.length) {
          tags.forEach((tag) => {
            if (this.checkboxTagsValues.includes(tag)) {
              this.checkboxSelectedTags.push(tag);
            }

            if (this.buttonsTagsValues.includes(tag)) {
              this.buttonsSelectedTags.push(tag);
            }
          });
        }

        this.refresh();
      }
    },
    siteFilter(newSiteFilter, oldSiteFilter) {
      if (!oldSiteFilter === '' || !newSiteFilter || this.hasInitialValue) return;

      this.checkboxSelectedTags.push(this.siteFilter);

      if (this.buttonsTagsValues.includes(this.siteFilter)) {
        this.buttonsSelectedTags.push(this.siteFilter);
      }

      this.refresh();
    }
  },
  created() {
    if (!this.pickerMode) {
      this.$store.subscribeAction((action, { url }) => {
        const currentTab = _get(action, 'payload.menu.status') || 'list',
          previousTab = url ? url.status : '';

        if (action.type === 'setHash' && currentTab === 'list' && previousTab && previousTab !== 'list') {
          this.refresh();
        }
      });
    }
  },
  methods: {
    // eslint-disable-next-line func-names
    debounceSearch: _debounce(function (resetSelection = false) {
      if (resetSelection) {
        this.$emit('deselectAll');
        this.sort.value = SORT_KEYS.RELEVANCE;
        this.sort.direction = DESC;
      }

      this.refresh();
    }, DEBOUNCE_TIME),
    /**
     * Changes the format of the date
     *
     * @param {Date} date
     * @returns {string}
     */
    customFormatDate(date) {
      return date.toLocaleDateString();
    },
    urlFiltersSetup() {
      this.settingFilters = true;
      const defaults = {
          sortValue: this.sort.value,
          sortDirection: this.sort.direction,
          offset: this.offset,
          startDate: this.startDate,
          endDate: this.endDate,
          limit: this.itemsPerPage
        },
        {
          search: paramSearch = '',
          sortValue = defaults.sortValue,
          sortDirection = defaults.sortDirection,
          offset = defaults.offset,
          startDate = defaults.startDate,
          endDate = defaults.endDate,
          limit = defaults.limit,
          collectionSlug = '',
          tags = [],
          username = ''
        } = parseUrlParameters(this.filteredList),
        decodedUsername = decodeURI(username);

      this.search = decodeURI(paramSearch) || this.search;
      this.sort = {
        value: decodeURI(sortValue),
        direction: decodeURI(sortDirection)
      };
      this.offset = parseInt(offset, 10);
      this.startDate = parseInt(startDate, 10);
      this.endDate = parseInt(endDate, 10);
      this.collectionSlug = decodeURI(collectionSlug);
      this.saveTags(decodeArray(tags));
      this.$emit('setItemsPerPage', parseInt(limit, 10));
      this.settingFilters = false;

      if (decodedUsername === ALL_USERS) {
        this.setUsernameFilter(allUsersOption);
        return Promise.resolve();
      }

      if (!decodedUsername || decodedUsername === this.usernameFilter.username) {
        return Promise.resolve();
      }

      return getUserByUsername(decodedUsername)
        .then((data) => {
          if (!hasStatusError(data)) {
            this.setUsernameFilter(data);
          }
        });
    },
    /**
     * Saves checkbox tags received into data
     * @param {string[]} tags
     */
    saveTags(tags = []) {
      this.checkboxSelectedTags = tags;
      // Quick filters should also be selected

      this.checkboxButtonsMatchingTags.forEach((tag) => {
        const indexButton = this.buttonsSelectedTags.indexOf(tag),
          validButtonIndex = indexButton >= 0,
          selectedTag = tags.includes(tag);

        if (!selectedTag && validButtonIndex) {
          this.$delete(this.buttonsSelectedTags, indexButton);
        } else if (selectedTag && !validButtonIndex) {
          this.buttonsSelectedTags.push(tag);
        }
      });

      if (!this.settingFilters) this.refresh();
    },
    /**
     * Get crop url parameters
     *
     * @param {string} item - Item in list
     * @returns {Object}
     */
    getCropUrlConf(item = { asset: { mimetype: '' } }) {
      return {
        referenceName: item.referenceName,
        width: ASSET_WIDTH,
        renditionKey: this.thumbnailRendition
      };
    },
    resetFilters() {
      this.sort = DEFAULT_SORT_CONF;
      this.uploadedYesterday = false;
      this.startDate = null;
      this.endDate = null;
      this.checkboxSelectedTags = [];
      this.buttonsSelectedTags = [];
      this.offset = 0;
      this.search = '';
      this.collectionSlug = '';
    },
    /**
     * Handles click in tags with filter buttons
     * @param {string} option
     */
    handleFilterButtonClick(option) {
      const indexButton = this.buttonsSelectedTags.indexOf(option),
        indexCheckbox = this.checkboxSelectedTags.indexOf(option),
        validButtonIndex = indexButton >= 0,
        validCheckboxIndex = indexCheckbox >= 0;

      if (!validButtonIndex && !validCheckboxIndex) {
        this.buttonsSelectedTags.push(option);

        if (this.checkboxButtonsMatchingTags.includes(option)) {
          this.checkboxSelectedTags.push(option);
        }
      }

      if (validButtonIndex) this.$delete(this.buttonsSelectedTags, indexButton);
      if (validCheckboxIndex) this.$delete(this.checkboxSelectedTags, indexCheckbox);

      this.refresh();
    },

    /**
     * set sort.value and sort.direction and refresh
     * @param {string} param - created|modified
     */
    setSort(param = '') {
      this.sort.direction = this.sort.value === param && this.sort.direction === DESC
        ? ASC
        : DESC;
      this.sort.value = param;

      this.refresh();
    },

    /**
     * Get the sort status
     * @param {string} val
     * @returns {string}
     */
    getSortStatus(val = '') {
      const { value = '' } = this.sort;

      return val === value;
    },

    /**
     * Get the direction of a sort value
     * @param {string} val
     * @returns {string }
     */
    getSortDirection(val = '') {
      const { value = '', direction = '' } = this.sort;

      return val && value === val ? direction : DESC;
    },

    /**
     * Run search query with current data
     */
    refresh() {
      const searchFilters = {
        collectionSlug: this.collectionSlug,
        search: this.search,
        tags: this.allSelectedTags,
        sortValue: this.sort.value,
        sortDirection: this.sort.direction,
        limit: this.itemsPerPage,
        offset: this.offset,
        startDate: this.startDate,
        endDate: this.endDate,
        username: this.usernameFilter.username || ALL_USERS,
        id: getIdFromPath(this.initialValue)
      };

      search(searchFilters)
        .then((data) => {
          if (hasStatusError(data)) {
            const {
              error = 'Unexpected Error',
              message = 'Search request failed'
            } = data;

            this.$emit('alert', { text: `${error}: ${message}` });
          } else {
            if (getStateUrlParameters(this.$store).status === 'list') {
              this.$emit('setFiltersInUrl', getNonDefaultParams(searchFilters));
            }
            const { total = 0, assets = [] } = data,
              // add selected to asset if id is in selected array
              assetsMapped = assets.map(asset => ({
                ...asset,
                selected: !!this.selected[asset.id]
              }));

            this.$emit('setAssets', assetsMapped);
            this.$emit('setTotal', total);

            if (this.forceRefresh) {
              this.$emit('resetForceRefresh');
            }

            if (this.paginationClicked) {
              this.$emit('scrollToTop', this.$refs['actions-container'].offsetHeight);
              this.paginationClicked = false;
            }
          }
        })
        .catch(console.error);
    },

    /**
     * Handles pagination click
     * @param {number} newOffset
     */
    handlePaginationClick(newOffset = 0) {
      this.paginationClicked = true;
      this.$emit('deselectAll');
      this.setOffset(newOffset);
    },
    /**
     * set the offset
     * @param {number} newOffset
     */
    setOffset(newOffset = 0) {
      this.offset = newOffset;
      this.refresh();
    },
    /**
     * Set items per page
     * @param {String} value
     */
    setItemsPerPage(value) {
      this.offset = 0;
      this.$emit('setItemsPerPage', value);
    },
    /**
     * Toggle uploaded yesterday state
     */
    toggleUploadedYesterday() {
      const newValue = !this.uploadedYesterday;

      this.$emit('setLastUpload', false);
      this.$emit('setAssets', []);
      this.$emit('setTotal', 0);

      if (newValue) {
        this.setItemsPerPage(ITEMS_PER_PAGE_OPTIONS[0]);
        this.startDate = startOfDay(subDays(new Date(), 1)).getTime();
        this.endDate = endOfDay(subDays(new Date(), 1)).getTime();
      } else {
        this.resetFilters();
      }

      this.uploadedYesterday = newValue;
      this.refresh();
    },
    /**
     * Handles all users option in user filter
     */
    handleAllUsers() {
      this.startDate = null;
      this.endDate = null;

      this.$emit('setLastUpload', false);
    },
    /**
     * Sets username filter object
     * @param {Object} usernameFilter
     */
    setUsernameFilter(usernameFilter = {}) {
      this.usernameFilter = usernameFilter;
    },
    handleCollectionSelection(text) {
      // only set value and execute search if the value actually changed
      if (text !== this.collectionSlug) {
        // set the value selected
        this.collectionSlug = text;
        // go to first page and execute search
        this.setOffset();
      }
    },
    /**
     * Reset custom date filters conditions
     */
    resetCustomDateFilters() {
      this.$emit('setLastUpload', false);
      this.uploadedYesterday = false;
    },
    /**
     * Set start date for results
     * @param {Number} value Time to be set in milliseconds
     */
    setStartDate(value) {
      this.resetCustomDateFilters();
      this.startDate = startOfDay(new Date(value)).getTime();
      this.offset = 0;

      this.refresh();
    },
    /**
     * Set end date for results
     * @param {Number} value Time to be set in milliseconds
     */
    setEndDate(value) {
      this.resetCustomDateFilters();
      this.endDate = endOfDay(new Date(value)).getTime();
      this.offset = 0;

      this.refresh();
    },
    /**
     * Get crop Url helper
     */
    getCropUrl,
    /**
     * Handle last upload state variable
     *
     * If unchecked, refresh results
     */
    handleLastUploadState() {
      this.uploadedYesterday = false;
      this.offset = 0;

      if (this.lastUpload) {
        this.resetFilters();
        this.refresh();
      } else {
        if (!this.pickerMode) {
          this.usernameFilter = USERNAME;
        }

        this.getLastestUploadTime()
          .then((time) => {
            if (time) {
              this.startDate = subMinutes(time, MINUTES_TO_SUBSTRACT).getTime();
              this.endDate = time;
              this.refresh();
            }
          })
          .catch(console.error);
      }

      this.$emit('setLastUpload', !this.lastUpload);
    },
    getLastestUploadTime() {
      return search({
        sortValue: SORT_KEYS.CREATED,
        sortDirection: DESC,
        limit: 1,
        username: this.usernameFilter.username,
        tags: this.allSelectedTags
      })
        .then((data) => {
          if (hasStatusError(data)) {
            const {
              error = 'Unexpected Error',
              message = 'Request to get latest upload batch failed'
            } = data;

            this.$emit('alert', { text: `${error}: ${message}` });
          } else {
            const { assets = [] } = data;

            if (assets.length > 0) return assets[0].uploadDate;
          }
        })
        .catch(console.error);
    }
  }
};
</script>
<style lang="scss" scoped>
  @import 'Styles/colors.scss';
  @import 'Styles/fonts.scss';
  @import 'Styles/helpers.scss';

  $crop-gap: 60px;
  $container-gap: 40px;
  $item-gap: 16px;

  ul.results {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    list-style-type: none;
    margin: 20px 0 0;
    padding-left: $container-gap;

    .small & {
      margin: 10px 0 0;
      padding-left: 6px;
    }

    > * {
      margin: 0 40px 30px 0;
      width: 240px;

      .small & {
        margin: 0;
        width: 187px;
      }
    }
  }

  .list-filters {
    align-items: center;
    border-bottom: 1px solid $border-color;
    display: flex;
    margin: 0 40px;
    padding-bottom: 15px;

    .small & {
      margin: 0 24px 0 0;
    }
  }

  .view-controls {
    color: $disable-color;
    display: inline-block;
    flex: 1;
    text-align: right;

    .small & {
      display: none;
    }
  }

  .sort-controls {
    align-items: center;
    display: flex;
    flex: 1;

    .sort-action {
      color: $disable-color;
      font-family: $default-font-family;
      font-size: 16px;
      text-transform: none;

      &.ui-button {
        height: inherit;
        padding-left: 10px;
        padding-right: 10px;
      }

      &.ui-button--type-primary.ui-button--color-default {
        background-color: transparent;
      }

      /deep/ {
        .ui-button__icon {
          color: $disable-color;
          margin-top: 0;
        }

        .ui-button__content {
          font-weight: inherit;
          letter-spacing: normal;
        }
      }

      &.active {
        color: $black;

         /deep/ {
          .ui-button__content {
            font-weight: bold;
          }

          .ui-button__icon {
            color: $black;
          }
         }
      }
    }

    .ui-icon {
      border: none;
      font-size: 22px;
      margin-right: 2px;
    }
  }

  .controls-title {
    color: $black;
    font-size: 16px;
    font-weight: bold;
    text-transform: uppercase;

    &.control-view {
      margin-left: $container-gap;
    }
  }

  .search-size {
    background-color: transparent;
    border: none;
    color: $disable-color;
    cursor: pointer;
    font-size: 16px;
    margin-left: 20px;
    padding: 0;

    &.active {
      color: $black;
      font-weight: bold;
    }

    &.clickable {
      cursor: pointer;
    }
  }

  .actions-container {
    display: flex;
    padding: 0 $container-gap $crop-gap;

    .small & {
      margin: 0 0 40px 0;
      padding: 0;
    }
  }

  .column {
    flex: 1 0 100%;

    &.left {
      flex: 1 1 100%;
      margin-right: 60px;
      padding-left: $container-gap;

      .small & {
        padding-left: 36px;
      }
    }

    &.right {
      flex: 1 1 auto;
      padding-right: $container-gap;

      .small & {
        padding-right: 0;
      }
    }
  }

  .search-pyxis {
    margin-bottom: 20px;

    /deep/ {
      .ui-textbox__label-text {
        font-size: 16px;
      }

      .ui-icon-button {
        height: auto;
        width: auto;

        &.ui-icon-button--type-secondary.ui-icon-button--color-default {
          &:hover:not(.is-disabled) {
            background-color: transparent;
          }
        }
      }

      .ui-icon.search {
        min-width: auto;
      }

      .ui-textbox__label-text.is-floating,
      .ui-textbox__feedback {
        font-size: $small-font-size;
      }
    }
  }

  .edit-controls {
    align-items: center;
    display: flex;
    padding: 20px 50px 0;

    .small & {
      padding: 20px 0 0;
    }
  }

  .edit-options,
  .results-info {
    flex: 1;
  }

  .results-info {
    margin-left: 40px;
  }

  .edit-options {
    text-align: right;

    > a {
      @extend .default-title;

      cursor: pointer;
      font-weight: bold;

      &.disabled {
        cursor: default;
        opacity: 0.4;
      }

      .ui-icon {
        font-size: 19px;
        padding: 0 25px 20px 0;
      }
    }
  }

  .filter-button {
    border-radius: 3px;
    border: solid 1px rgba(0, 0, 0, 0.54);
    color: $border-color-darker;
    font-family: $default-font-family;
    font-size: $standard-font-size;
    margin-bottom: 0px;
    margin-right: 12px;
    padding: 7px 12px;
    text-transform: none;

    &.active {
      background-color: $gray;
    }

    /deep/ .ui-button__content {
      font-weight: inherit;
    }
  }

  .metadata-modal {
    padding-left: 30px;
  }

  .selection-btn,
  .deselection-btn {
    margin-right: 20px;
    padding: 0 16px;

    &.is-disabled {
      opacity: 0.4;
    }
  }

  .filter-buttons {
    display: flex;
    margin-bottom: 14px;
  }

  // datepicker styles
  .ui-datepicker {
    &.has-floating-label /deep/ {
      .is-floating {
        font-size: $small-font-size;
      }

      .ui-datepicker__display-value {
        font-size: $standard-font-size;
      }

      .ui-datepicker__label-text.is-inline {
        font-size: $standard-font-size;
        transform: translateY(1.625rem) scale(1);
      }
    }
  }

  // select styles
  .ui-select {
    @extend .select-nowrap-style;

    margin-bottom: 0;

    &.has-floating-label /deep/ .ui-select__label-text {
      &.is-floating {
        font-size: $small-font-size;
        margin-top: 3px;
      }

      &.is-inline {
        transform: translateY(1.625rem) scale(1);
      }
    }

    /deep/ {
      .ui-select__display {
        height: 2rem;
        padding: 0;
      }

      .ui-select__label-text,
      .ui-select-option,
      .ui-select__display-value {
        font-size: $standard-font-size;
      }
    }
  }

  @media screen and (min-width: 1440px) {
    .search-filters {
      align-items: center;
      display: flex;
    }

    .datepicker-container {
      display: flex;
      flex: 1;

      .ui-datepicker {
        margin-bottom: 14px;
        width: 50%;

        /deep/ .is-floating {
          margin-bottom: 3px;
        }
      }

      .ui-datepicker:last-child {
        margin-left: 12px;
      }
    }

    .tags-filters {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;

      > .filter {
        flex-grow: 1;
        margin-right: 12px;
        width: 32%;

        &:last-child {
          margin-right: 0;
        }
      }
    }
  }
</style>
