<template>
  <div v-scroll-lock="true" class="custom-main-search">
    <FieldSearchRequest
      :herited-options="{ display: 'main' }"
      :in="queryFilters"
      :limit="200"
      :search-key="searchKey"
      :placeholder="$_tr('placeholder')"
      @requestValidated="requestValidated"
      @resetSearch="resetSearch"
    />

    <div
      class="custom-main-search__cross df-center-y"
      @click="closeSearch({}, true)"
    >
      <span>{{ $_tr('close') }}</span>

      <i class="sid2-more" />
    </div>

    <div class="custom-main-search__infos">
      <ul v-if="!getTablet" class="custom-main-search__infos-filters">
        <li
          v-for="(filter, index) in filtersSorted"
          :key="index"
          :class="[
            (queryFilters.indexOf(filter.type) > -1 &&
              queryFilters.length !== allowedFilters.length) ||
              (filter.type === 'all' &&
                queryFilters.length === allowedFilters.length)
              ? 'filter-active'
              : '',
            `custom-main-search__infos-filters--${filter.type}`
          ]"
          @click="updateFilter(filter.type)"
        >
          <span>{{ filter.title }}</span>
        </li>
      </ul>

      <template v-else>
        <DefaultSlideshow
          v-if="searchableContentTypes.length > 0"
          :arrows-enabled="true"
          :data="filtersSorted"
          class="custom-main-search__infos-filters"
          @onSlideshowMount="detectSlideshowChanges"
        >
          <template #default="{ item: filter }">
            <div
              :key="filter.uuid"
              class="filter-slideshow"
              :class="{
                'filter-active':
                  queryFilters.indexOf(filter.type) > -1 ||
                  (filter.type === 'all' &&
                    queryFilters.length === allowedFilters.length)
              }"
            >
              <span>{{ filter.title }}</span>
            </div>
          </template>
        </DefaultSlideshow>
      </template>
    </div>

    <div
      v-if="isLoading"
      v-scroll-lock="true"
      class="custom-main-search__results main-search__results-loading"
    >
      <loader-ui />
    </div>

    <div v-else v-scroll-lock="true" class="custom-main-search__results">
      <div v-if="results && results[0]">
        <ResumeSearches
          v-for="(result, index) in results"
          :key="`index-${index}`"
          :data="result"
        />

        <pagination-ui
          v-if="totalPages > 1 && usePagination"
          :current-page="currentPage"
          :total-pages="totalPages"
          @onPageChange="setCurrentPage"
        />
      </div>

      <div
        v-else-if="currentSearchModel.length > 3"
        class="custom-main-search__results--empty df-center-xy"
      >
        <BaseText>{{ $_tc('empty', [searchKey]) }} ...</BaseText>
      </div>
    </div>
  </div>
</template>

<script>
import { BaseText } from 'inside-collection/atoms'
import DefaultSlideshow from '@inside-slideshow/components/lib/Default'

import FieldSearchRequest from './fields/FieldSearchRequest'
import GlobalSearchMixin from './mixins/global-search-mixin'
import ResumeSearches from './resume/ResumeSearches'

export default {
  name: 'MainSearches',
  $_i18nRootPath: 'customs.SEARCHES.main',
  components: {
    FieldSearchRequest,
    DefaultSlideshow,
    ResumeSearches,
    BaseText
  },
  mixins: [GlobalSearchMixin],
  data() {
    return {
      currentSearchModel: '',
      queryFilters: this.$store.getters.getSearchAllowedFilters || [],
      results: this.$store.getters.getSearchResults('welcome-search')
        ? this.$store.getters.getSearchResults('welcome-search')
        : [],
      resultHeight: null,
      isLoading: false,
      searchRequestWaiting: 0,
      searchRequestComplete: 0,
      searchKey: 'main-search',
      currentPage: 1,
      totalPages: 0
    }
  },
  computed: {
    filtersSorted() {
      const sortedFilters = this.searchableContentTypes.sort((a, b) => {
        return a.title.localeCompare(b.title)
      })

      return [
        {
          title: this.$_tr('all'),
          type: 'all'
        },
        ...sortedFilters
      ]
    },
    usePagination() {
      return this.$_getConfig('usePaginationForMain', 'inside-searches')
    }
  },
  watch: {
    allowedFilters: {
      handler: function (data) {
        this.queryFilters = data
      },
      deep: true
    },
    getCurrentPath() {
      this.setStoreAction('setSearchOpen', false)
    }
  },
  beforeUnmount() {
    document.removeEventListener('keyup', this.closeSearch)
  },
  mounted() {
    document.addEventListener('keyup', this.closeSearch)
    this.currentSearchModel = this.$store.getters.getSearchQuery('main-search')

    if (this.currentSearchModel) this.requestValidated()
  },
  methods: {
    /*
     * Close main search method, by click or escape key hit
     *
     * @param {event} e
     * @param {boolean} fromClick
     */
    closeSearch(e, fromClick) {
      // Escape on keyboard
      if (e.keyCode === 27 || fromClick) {
        this.setStoreAction('setSearchOpen', false)
        this.setStoreAction('resetSearch')
      }
    },
    /*
     * Make search request
     */
    requestValidated(searchModel) {
      this.isLoading = true

      if (
        this.currentSearchModel !==
          this.$store.getters.getSearchQuery('main-search') &&
        this.usePagination
      ) {
        this.currentPage = 1
      }

      this.currentSearchModel =
        this.$store.getters.getSearchQuery('main-search')

      const params = {
        params: {
          query: this.currentSearchModel,
          page: this.currentPage,
          filters: JSON.stringify({
            in: this.queryFilters,
            langcode: this.$_currentLang,
            limit: 8,
            status: 1
          }),
          fields: JSON.stringify([
            'uuid',
            'title',
            'published_at',
            {
              parent_tree: {
                fields: ['uuid', 'slug'],
                filters: {
                  content_type: 'folders',
                  reverse: true,
                  sort: 'title:asc'
                }
              }
            }
          ])
        }
      }

      this.searchRequestWaiting++

      this.get('search', params).then(
        response => {
          this.searchRequestComplete++

          if (this.searchRequestComplete === this.searchRequestWaiting) {
            this.isLoading = false
            this.totalPages = response.data.last_page
            this.results = response.data.data
          }
        },
        err => {
          this.$_triggerErrorToast({
            text: err
          })
        }
      )
    },
    /*
     * Mobile device filters slideshow management - make a filtered request on filter change
     */
    detectSlideshowChanges(slider) {
      slider.on('slideChange', () => {
        const index = slider.realIndex

        this.queryFilters = []
        if (index > 0) {
          const filter = this.searchableContentTypes[index - 1]

          if (filter.type === 'all') {
            this.queryFilters = this.allowedFilters
          } else {
            this.queryFilters = [filter.type]
          }
        }

        this.requestValidated()
      })
    },
    /*
     * Manage desktop filter list / filtered requests
     *
     * @param {String} filter
     */
    updateFilter(filter) {
      if (filter === 'all') {
        this.queryFilters = this.allowedFilters
      } else {
        if (this.queryFilters.length === this.allowedFilters.length) {
          this.queryFilters = []
        }

        const item = this.queryFilters.indexOf(filter)

        if (item < 0) {
          this.queryFilters.push(filter)
        } else {
          this.queryFilters.splice(item, 1)
        }

        if (this.queryFilters.length === 0) {
          this.queryFilters = this.allowedFilters
        }
      }

      if (this.usePagination) {
        this.currentPage = 1
      }

      this.requestValidated()
    },
    /*
     * Reset search model, filters and results
     */
    resetSearch() {
      this.searchModel = ''
      this.currentPage = 1
      this.queryFilters = this.allowedFilters
      this.results = []
    },
    setCurrentPage(index) {
      this.currentPage = index

      this.requestValidated()
    }
  }
}
</script>
<style scoped lang="scss">
@use '../../styles/modules/inside-customs/searches/main.scss' as *;
</style>
