<!-- Search for events -->

<template>
  <LayoutContainer>
    <!-- Search form -->
    <v-row class="my-3" id="searchBar">
      <v-col cols="1"></v-col>
      <v-col cols="10">
        <v-card class="px-4" rounded="lg" :elevation="6">
          <v-form method="get" class="mt-8 w100">
            <v-container>
              <v-row>
                <v-col cols="12" md="4" class="py-2 px-1">
                  <UiSearchDateRangePicker
                    ref="dateSearch"
                    v-model="dateRangeFilter"
                    :label="$t('when') + ' ?'"
                    preset-label=""
                    separator-label="-"
                    :presets="dateRangePresets"
                    :min="dateRangeMin"
                    locale="fr-FR"
                    no-title
                    display-format="dd/MM/yyyy"
                    :inputProps="{outlined: true}"
                    :menuProps="{offsetY: true, closeOnContentClick: false}"
                    :actionLabels="{apply: $t('apply'), cancel: $t('cancel'), reset: $t('reset')}"
                    @input="dateRangeFilterChanged"
                  >
                  </UiSearchDateRangePicker>
                </v-col>

                <v-col cols="12" md="4" class="py-2 px-1">
                  <UiSearchAddress
                    ref="addressSearch"
                    type="municipality"
                    @change="locationFilterChanged"
                  />
                </v-col>

                <v-col cols="12" md="4" class="py-2 px-1">
                  <v-text-field
                    v-model="textFilter"
                    type="text"
                    outlined
                    clearable
                    hide-details
                    append-icon="mdi-magnify"
                    :label="$t('what') + ' ?'"
                    @click:append="search"
                    @keydown.enter="search"
                  />
                </v-col>
              </v-row>

              <v-row class="search-actions" justify="space-around">
                <v-col cols="12" sm="5" md="3">
                  <v-btn @click="reinitializeFilters">
                    {{ $t('reinitialize') }}
                  </v-btn>
                </v-col>
                <v-col cols="12" sm="5" md="3">
                  <v-btn class="h100" @click="search()" style="width: 100%;">
                    {{ $t('search') }}
                  </v-btn>
                </v-col>
              </v-row>
            </v-container>
          </v-form>
        </v-card>
      </v-col>
      <v-col cols="1"></v-col>
    </v-row>

    <v-row>
      <!-- loading skeleton -->
      <v-container v-if="$fetchState.pending" style="width: 100%">
        <v-row v-for="i in 4" :key="i" justify="center" justify-sm="start">
          <v-col
            v-for="j in 4"
            :key="j"
            :cols="12"
            :sm="6"
            :md="4"
            :lg="3"
            class="py-2 px-2 my-2"
          >
            <v-skeleton-loader type="card-avatar, article, button" :loading="true" height="400px" />
          </v-col>
        </v-row>
      </v-container>

      <!-- Results -->
      <v-data-iterator
        v-else
        :items="events"
        :page.sync="page"
        :items-per-page="itemsPerPage"
        sort-by="name"
        hide-default-footer
        :no-data-text="$t('no_results')"
        style="width: 100%"
      >
        <template #header>
          <i class="results-count">{{ totalRecords }} {{ $t('results') }}</i>
        </template>
        <template #default="props">
          <v-container>
            <v-row
              justify="center"
              justify-sm="start"
            >
              <v-col
                v-for="publicEvent in events"
                :key="publicEvent.uuid"
                :cols="12"
                :sm="6"
                :md="4"
                :lg="3"
                class="py-2 px-2 my-2"
              >
                <v-card
                  elevation="4"
                  class="event-card pa-0 d-flex flex-column"
                >
                  <div class="d-flex justify-center max-w100">
                    <v-img
                      :src="publicEvent.thumbnailUrl || '/images/event-default.jpg'"
                      alt="poster"
                      max-width="100%"
                      max-height="100%"
                      :contain="true"
                      tile
                    />
                  </div>

                  <div class="d-flex flex-column flex-grow-1 px-3">
                    <v-card-title class="title">
                      <nuxt-link :to="{path: '/events/' + publicEvent.uuid, query: query}">
                        {{ publicEvent.name }}
                      </nuxt-link>
                    </v-card-title>

                    <v-card-text class="infos pb-0">
                      <table>
                        <tr v-if="publicEvent.datetimeStart" class="pa-1">
                          <td class="pt-1">
                            <font-awesome-icon :icon="['fas', 'calendar']" class="icon mr-2" />
                          </td>
                          <td class="pa-1">
                            <span>
                              {{ dateUtils.formatDateIntervalFor(new Date(publicEvent.datetimeStart), new Date(publicEvent.datetimeEnd)) }}
                            </span>
                          </td>
                        </tr>

                        <tr v-if="publicEvent.address.addressCity">
                          <td class="pt-1">
                            <font-awesome-icon class="icon" :icon="['fas', 'map-marker-alt']" />
                          </td>
                          <td class="pa-1">
                            <span v-if="publicEvent.roomName" style="white-space: pre-line;">{{ publicEvent.roomName }}<br></span>
                            <span v-if="publicEvent.address.streetAddress" style="white-space: pre-line;">{{ publicEvent.address.streetAddress }}<br></span>
                            <span>{{ publicEvent.address.addressCity }}</span>
                          </td>
                        </tr>
                      </table>
                    </v-card-text>
                  </div>

                  <v-card-actions class="align-self-end pa-3">
                    <v-btn
                      class="see"
                      :to="{path: '/events/' + publicEvent.uuid, query: query}"
                      nuxt
                    >
                      <span style="margin-right: 6px;">{{ $t("more_to_know") }}</span>
                      <font-awesome-icon :icon="['fa', 'caret-right']" />
                    </v-btn>
                  </v-card-actions>
                </v-card>
              </v-col>
            </v-row>
          </v-container>
        </template>
        <template #footer>
          <v-pagination
            v-model="page"
            :length="pagesCount"
            total-visible="9"
            color="primary"
            class="my-5"
            @input="pageUpdated"
          />
        </template>
      </v-data-iterator>
    </v-row>
  </LayoutContainer>
</template>

<script lang="ts">
import Vue from 'vue'
import EventsProvider from "~/services/data/EventsProvider"
import DatesUtils from "~/services/utils/dateUtils";

const defaultDateRange: DateRange = { start: '', end: '' }

export default Vue.extend({
  scrollToTop: true,
  data () {
    return {
      theme: this.$route.query.theme as string ?? 'orange',
      organization: parseInt(this.$route.query.organization as string) ?? null,
      page: 1,
      events: [] as Array<PublicEvent>,
      itemsPerPage: 16,
      textFilter: null as string | null,
      locationFilter: null as Coordinates | null,
      dateRangeFilter: defaultDateRange,
      totalRecords: 0 as number,
      pagesCount: 1 as number | null,
      dateUtils: new DatesUtils(this.$dateFns, this.$t, this.$i18n)
    }
  },
  async fetch () {
    await new EventsProvider(this.$axios).getBy(
      this.textFilter,
      this.organization,
      this.dateRangeFilter.start,
      this.dateRangeFilter.end,
      this.locationFilter,
      this.page,
      this.itemsPerPage
    ).then(
      (collection: HydraCollection<PublicEvent>) => {
        this.events = collection.items
        this.totalRecords = collection.totalItems
        this.page = collection.page ?? 1
        this.pagesCount = collection.lastPage ?? 1
      })
  },
  computed: {
    query (): object {
      const q: any = { theme: this.theme }
      if (this.organization > 0) {
        q.organization = this.organization
      }
      return q
    },
    dateRangeMin(): string {
      return this.dateUtils.todayIso()
    },
    dateRangePresets(): Array<DateRangePreset> {
      // Today
      const today_preset: DateRangePreset = {
        label: this.$t('today').toString(),
        range: {start: this.dateUtils.todayIso(), end: this.dateUtils.todayIso()}
      }

      // Cette semaine
      const week_preset: DateRangePreset = {
        label: this.$t('next_week').toString(),
        range: {start: this.dateUtils.todayIso(), end: this.dateUtils.formatIso(this.$dateFns.addDays(this.dateUtils.today(), 7))}
      }

      // Ce week-end
      const sunday: Date = this.$dateFns.nextSunday(this.dateUtils.today())
      const weekend_preset: DateRangePreset = {
        label: this.$t('next_weekend').toString(),
        range: {start: this.dateUtils.formatIso(this.$dateFns.addDays(sunday, -2)), end: this.dateUtils.formatIso(sunday)}
      }

      // Ce mois
      const month_preset: DateRangePreset = {
        label: this.$t('next_month').toString(),
        range: {start: this.dateUtils.todayIso(), end: this.dateUtils.formatIso(this.$dateFns.addMonths(this.dateUtils.today(), 1))}
      }

      return [today_preset, week_preset, weekend_preset, month_preset]
    }
  },
  methods: {
    textFilterChanged (newVal: string) {
      this.textFilter = newVal
    },
    locationFilterChanged (newVal: Coordinates) {
      this.locationFilter = newVal
      this.search()
    },
    dateRangeFilterChanged (newVal: DateRange) {
      this.dateRangeFilter = newVal
      this.search()
    },
    reinitializeFilters (): void {
      this.textFilter = null
      this.locationFilter = null
      this.dateRangeFilter = defaultDateRange
      const dateSearch = this.$refs.dateSearch as any
      dateSearch.reset()
      const addressSearch = this.$refs.addressSearch as any
      addressSearch.clear()
      this.page = 1
      this.search()
    },
    async pageUpdated (page: number): Promise<void> {
      await this.$vuetify.goTo(0, { duration: 400, offset: 0, easing: 'easeInOutCubic' })
      this.page = page
      this.search()
    },
    /**
     * Update the filteredEvents array
     */
    search (): void {
      this.$fetch()
    },
    /**
     * Enhanced filter for v-autocomplete components
     *
     * @param _
     * @param queryText
     * @param itemText
     */
    enhancedAutocompleteFilter (_: any, queryText: string, itemText: string): boolean {
      return normalize(itemText).includes(normalize(queryText))
    }
  }
})
</script>

<style scoped lang="scss">
@import 'assets/style/variables.scss';

h2 {
  color: var(--v-primary-base);
}

.event-card {
  height: 100%;
  width: 280px;
  min-width: 280px;
  color: #666666;
}

.event-card .title {
  text-transform: uppercase;
}

.event-card .title a {
  width: 100%;
  text-align: center;
}

.infos td {
  vertical-align: top;
  text-transform: capitalize;
}

.title {
  word-break: normal;
  color: var(--v-primary-base);
  font-size: 18px;
  font-weight: 500;
  line-height: 1.6rem;
}

.title a {
  text-decoration: none;
}

.icon {
  color: var(--v-primary-base);
}

.results-count {
  font-size: .8em;
  color: #666;
}

.search-actions button {
  width: 100%;
  height: 36px !important;
}


</style>
