<template>
  <div class="spaces-listing-container">
    <div class="header">
      <filters-container :id="filtersId" :filters="filters" />

      <div v-if="hasAccess" class="buttons-container">
        <Link
          :href="{
            name: 'AdminResponsesPage',
            params: { slug: 'ajouter-un-collaborateur' }
          }"
          :inline="false"
        >
          <Button appearance="secondary" type="admin" size="small">
            {{ $_tr('button.add') }}
          </Button>
        </Link>

        <Link
          :href="{
            name: 'AdminResponsesPage',
            params: { slug: 'supprimer-un-collaborateur' }
          }"
          :inline="false"
        >
          <Button appearance="secondary" type="admin" size="small">
            {{ $_tr('button.delete') }}
          </Button>
        </Link>
      </div>
    </div>

    <component-listing
      v-if="!hasAccess ? requestDone : true"
      id="franchised-spaces-listing"
      endpoint="content/franchised_spaces"
      :fields="requestFields"
      :filters="requestFilters"
      :filter-id="filtersId"
      :static-data="!hasAccess ? spaces : null"
      :items-per-page="9"
      :search-in="['franchised_spaces']"
      direction="horizontal"
    >
      <template #default="{ item }">
        <Link
          :inline="false"
          :href="{ name: 'SpacePage', params: { slug: item.slug[0] } }"
        >
          <CardImageWithEdition
            v-bind="item"
            :key="item.uuid"
            :image="$_getContentImage(item.image, 'image-card')"
          />
        </Link>
      </template>
    </component-listing>
  </div>
</template>

<script>
import { http } from '@inside-library/helpers/Http'
import { storage } from '@inside-library/helpers/Storage'
import { Button, CardImage, Link } from 'inside-collection/components'
import { isSuperAdmin, isAdmin } from '@inside-library/helpers/Rights'

import { withEdition } from '@inside-edition/hocs'

export default {
  name: 'SpacesListing',
  $_i18nRootPath: 'customs.SPACE.LISTING',
  components: {
    Button,
    CardImageWithEdition: withEdition(CardImage),
    Link
  },
  data() {
    return {
      filtersId: 'spaces-listing-customs-filters',
      maxItems: 9,
      spaces: [],
      requestFields: [
        'uuid',
        'title',
        'image',
        'slug',
        'admin',
        'content_type'
      ],
      requestDone: false,
      hasAccess: null
    }
  },
  computed: {
    requestFilters() {
      return this.hasAccess
        ? { 'status:eq': 1 }
        : { 'uuid:eq': this.getUserInfos.uuid, 'status:eq': 1 }
    },
    filters() {
      return [
        {
          modelName: 'search',
          type: 'text',
          label: this.$_tr('filters.search')
        }
      ]
    }
  },
  beforeMount() {
    const user = storage.get('current-user')
    this.hasAccess =
      isSuperAdmin() ||
      isAdmin() ||
      user.permissions.roles.includes('Rédacteur en chef') ||
      user.permissions.roles.includes('Rédacteur')

    if (!this.hasAccess) {
      this.fetchData()
    }
  },
  methods: {
    async fetchData() {
      try {
        const { data } = await http.get('content/users', {
          fields: [{ franchised_spaces: ['uuid'] }],
          filters: { 'uuid:eq': this.getUserInfos.uuid, 'status:eq': 1 }
        })

        const uuidSpaces = this.getCheckedData(
          data,
          [0, 'franchised_spaces', 'uuid'],
          []
        )

        const { data: spaces } = await http.get('content/franchised_spaces', {
          fields: this.requestFields,
          filters: { 'uuid:eq': uuidSpaces, 'status:eq': 1 }
        })
        this.spaces = spaces
        this.requestDone = true
      } catch (err) {
        throw new Error(err)
      }
    }
  }
}
</script>

<style lang="scss">
.spaces-listing-container {
  > .header {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    flex-wrap: wrap;

    > div {
      margin-top: var(--spacing-s);
    }

    .filters-container {
      min-width: 300px;
      max-width: 500px;
    }

    .buttons-container {
      > a {
        display: inline-block;
        margin: var(--spacing-xs) 0;

        &:first-child {
          margin-right: var(--spacing-xs);
        }
      }
    }
  }
}
</style>
