<!-- Search for events -->

<template>
  <LayoutContainer>
    <!-- Search form -->
    <v-row class="my-3">
      <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"
                    :start-label="$t('start_date')"
                    :end-label="$t('end_date')"
                    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')}"
                  >
                  </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">
        <v-row v-for="i in 4" :key="i" justify="space-between" class="mt-1 mb-3">
          <v-col v-for="j in 4" :key="j" cols="3" :md="6" class="py-2 px-1">
            <v-skeleton-loader type="card-avatar, text, button" :loading="true" />
          </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=""
        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="event in props.items"
                :key="event.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
                      v-if="event.imageId"
                      :src="'https://api.opentalent.fr/app.php/_internal/secure/files/' + event.imageId"
                      alt="poster"
                      height="160"
                      width="100%"
                      max-height="100%"
                      :contain="true"
                      tile
                    />
                    <div v-else style="height: 184px;" />
                  </div>

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

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

                        <tr v-if="event.address.addressCity">
                          <td class="pt-1">
                            <font-awesome-icon class="icon" :icon="['fas', 'map-marker-alt']" />
                          </td>
                          <td class="pa-1">
                            <span v-if="event.roomName" style="white-space: pre-line;">{{ event.roomName }}<br></span>
                            <span v-if="event.address.streetAddress" style="white-space: pre-line;">{{ event.address.streetAddress }}<br></span>
                            <span>{{ event.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: '/event/' + event.uuid, query: { theme: theme, hideTitle: hideTitle }}"
                      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 {today, todayIso, formatIso} from '@/services/utils/date'
import locale from 'date-fns/locale/fr'

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

export default Vue.extend({
  data () {
    return {
      theme: this.$route.query.theme ?? 'orange',
      hideTitle: this.$route.query.hideTitle === 'true',
      events: [] as Array<PublicEvent>,
      page: 1,
      itemsPerPage: 16,
      textFilter: null as string | null,
      locationFilter: null as Coordinates | null,
      dateRangeFilter: defaultDateRange,
      totalRecords: 0 as number,
      pagesCount: 1 as number | null,
    }
  },
  async fetch () {
    await new EventsProvider(this.$axios).getBy(
      this.textFilter,
      null,
      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

        console.log(this.events)
      })
  },
  computed: {
    dateRangeMin(): string {
      return todayIso()
    },
    dateRangePresets(): Array<DateRangePreset> {
      // Today
      const today_preset: DateRangePreset = {
        label: this.$t('today').toString(),
        range: {start: todayIso(), end: todayIso()}
      }

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

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

      // Ce mois
      const month_preset: DateRangePreset = {
        label: this.$t('next_month').toString(),
        range: {start: todayIso(), end: formatIso(this.$dateFns.addMonths(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 addressSearch = this.$refs.addressSearch as any
      addressSearch.clear()
      this.search()
    },
    pageUpdated (page: number): void {
      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))
    },
    formatDate(date: Date, short = true): string {
      return short ? this.$dateFns.format(date, 'dd/MM/yyyy') : this.$dateFns.format(date, 'dd MMM yyyy', {locale: locale})
    },
    formatTime(date: Date): string {
      return this.$dateFns.format(date, 'HH:mm')
    },
    formatDateTime(date: Date): string {
      return this.formatDate(date) + ' ' + this.$t('on_hour') + ' ' + this.formatTime(date)
    },
    formatDateIntervalFor(dateStart: Date | null = null, dateEnd: Date | null = null): string {
      if (dateStart === null && dateEnd !== null)
      {
        return this.formatDateTime(dateEnd)
      }
      else if (dateEnd === null && dateStart !== null) {
        return this.formatDateTime(dateStart)
      }
      else if (dateStart !== null && dateEnd !== null) {
        if (dateStart === dateEnd) {
          return this.formatDateTime(dateStart)
        }
        else if (this.$dateFns.isSameDay(dateStart, dateEnd)) {
          return this.formatDate(dateStart, false) + ', ' +
            this.formatTime(dateStart) + ' - ' + this.formatTime(dateEnd)
        }
        else {
          return this.$t('from_day') + ' ' + this.formatDateTime(dateStart) + ' ' + this.$t('to_day') + ' ' + this.formatDateTime(dateEnd)
        }
      }
      return ""
    }
  }
})
</script>

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

//* {
//  font-family: ;
//}

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>
