<template>
  <div class="file-nav-ged">
    <BreadcrumbGed />

    <!-- GED classic display -->
    <template v-if="currentData">
      <transition name="fadeIn" mode="out-in">
        <div v-if="!getGEDSearchStatus" :key="getGEDSearchStatus">
          <MultiUploadButton
            v-if="
              allowToAddContents &&
                getCurrentFolder &&
                getCurrentFolder.is_media_folder
            "
            :current-folder="getCurrentFolder.uuid"
          />

          <HeaderListGed
            :heritedData="currentData"
            :disableToggleDisplay="disableToggleDisplay"
            @displayListStatus="toggleDisplayList"
          />

          <transition name="fadeIn" mode="out-in">
            <div
              v-if="!currentData.is_media_folder || displayList"
              class="file-nav-ged__body"
            >
              <!-- Folders -->
              <div
                v-if="getFolders.length > 0"
                class="file-nav-ged__body-folder"
                :class="{
                  'file-nav-ged__body-folder--noborder': !isAlive(currentData, [
                    getCurrentContentType(),
                    'data',
                    0
                  ])
                }"
              >
                <template v-for="folder in getFolders" :key="folder.uuid">
                  <ListGed :heritedData="folder" />
                </template>
              </div>

              <!-- Documents -->
              <div class="file-nav-ged__body-files">
                <template v-if="isAlive(currentData, ['documents', 'data', 0])">
                  <ListGed
                    v-for="(file, index) in currentData[getCurrentContentType()]
                      .data"
                    :key="file.uuid"
                    :index="index"
                    :album-data="currentData['photo'].data"
                    :heritedData="file"
                  />
                </template>

                <!-- Declined documents without document -->
                <template
                  v-if="isAlive(currentData, ['declined_documents', 'data', 0])"
                >
                  <ListGed
                    v-for="(file, index) in currentData['declined_documents']
                      .data"
                    :key="file.uuid"
                    :index="+index"
                    :is-declension="true"
                    :heritedData="file"
                  />
                </template>
              </div>

              <div class="file-nav-ged__body-files">
                <!-- SOPs -->
                <template v-if="isAlive(currentData, ['sops', 'data', 0])">
                  <list-ged
                    v-for="(file, index) in currentData['sops'].data"
                    :key="file.uuid"
                    :index="+index"
                    :heritedData="file"
                  />
                </template>

                <!-- ROPs without SOP -->
                <template v-if="isAlive(currentData, ['rops', 'data', 0])">
                  <ListGed
                    v-for="(file, index) in currentData['rops'].data"
                    :key="file.uuid"
                    :index="+index"
                    :is-declension="true"
                    :heritedData="file"
                  />
                </template>
              </div>
            </div>

            <!-- IsMediatheque -->
            <div v-else class="file-nav-ged__body cards-wrapper">
              <!-- Folders card (albums) -->
              <div
                v-if="
                  isAlive(currentData, [
                    getCurrentContentType('folders'),
                    'data',
                    0
                  ])
                "
                :class="{
                  'file-nav-ged__body-album--noborder': !isAlive(currentData, [
                    getCurrentContentType(),
                    0
                  ])
                }"
                class="file-nav-ged__body-album"
              >
                <CardGed
                  v-for="(album, index) in currentData[
                    getCurrentContentType('folders')
                  ].data"
                  :key="album.id"
                  :heritedData="album"
                  :index="+index"
                />
              </div>

              <!-- Media card (pictures) -->
              <div
                v-if="isAlive(currentData, ['photo', 'data', 0])"
                class="file-nav-ged__body-media"
              >
                <template
                  v-for="(file, index) in currentData['photo'].data"
                  :key="file.id"
                >
                  <CardGed
                    :heritedData="file"
                    :album-data="currentData['photo'].data"
                    :index="+index"
                  />
                </template>

                <div
                  :style="{ width: '100%' }"
                  class="album-footer df-center-y"
                >
                  <like-ui
                    :heritedData="{
                      type: 'like',
                      related_uuid: currentData.uuid,
                      related_type: currentData.content_type,
                      reactions: currentData.reactions
                    }"
                  />

                  <a
                    :href="`/protected_files/albums/${currentData.uuid}.zip`"
                    class="btn download-cta ebook-cta"
                    download
                  >
                    <i class="sid2-download" />

                    {{ $_tr('download') }}
                  </a>
                </div>
              </div>
            </div>
          </transition>

          <div
            v-if="
              !isAlive(currentData, ['folders', 'data', 0]) &&
                !isAlive(currentData, ['documents', 'data', 0]) &&
                !isAlive(currentData, ['declined_documents', 'data', 0]) &&
                !isAlive(currentData, ['sops', 'data', 0]) &&
                !isAlive(currentData, ['rops', 'data', 0]) &&
                !isAlive(currentData, ['photo', 'data', 0]) &&
                !$store.getters.getLoadingGEDStatus
            "
            class="file-nav-ged__no-docs"
          >
            <BaseText>{{ $_tr('document.empty') }}</BaseText>
          </div>

          <div
            v-else-if="$store.getters.getLoadingGEDStatus"
            class="loading-overlay"
          >
            <LoaderUi />
          </div>
        </div>

        <!-- Search Results -->
        <div v-else :key="getGEDSearchStatus" class="file-nav-ged__results">
          <!-- Results are received from request -->
          <template v-if="!getLoadingGEDStatus">
            <div class="file-nav-ged__results__count">
              <BaseText v-if="getSearchQuery.query.length < 3">
                {{ $_tc('characters.minimum', 3) }}
              </BaseText>

              <BaseText v-else-if="searchData">
                {{
                  $_tc('search.results', searchData ? searchData.length : 0, [
                    searchData ? searchData.length : 0,
                    getSearchQuery.query
                  ])
                }}
              </BaseText>

              <BaseText v-else>{{ $_tr('search.empty') }}</BaseText>
            </div>

            <HeaderListGed
              :heritedData="{ is_media_folder: false }"
              :disableToggleDisplay="disableToggleDisplay"
            />

            <div class="file-nav-ged__results__content">
              <div
                v-if="searchData && searchData.length > 0"
                class="file-nav-ged__body"
              >
                <div class="file-nav-ged__body-folder">
                  <ListGed
                    v-for="doc in searchData"
                    :key="doc.uuid"
                    :heritedData="doc"
                  />
                </div>
              </div>

              <div
                v-if="getSearchQuery.query.length >= 3 && !searchData"
                class="file-nav-ged__results__no-content"
              >
                <BaseText>{{ $_tr('search.empty') }}</BaseText>
              </div>
            </div>
          </template>

          <!-- Results are loading -->
          <template v-else>
            <div class="file-nav-ged__results__count">
              <BaseText>{{ $_tr('search.inProgress') }}</BaseText>
            </div>

            <HeaderListGed
              :heritedData="{ is_media_folder: false }"
              :disableToggleDisplay="disableToggleDisplay"
            />
          </template>
        </div>
      </transition>
    </template>
  </div>
</template>

<script>
import BreadcrumbGed from './BreadcrumbGed'
import CardGed from './files/CardGed'
import ListGed from './files/ListGed'
import HeaderListGed from './HeaderListGed'
import MultiUploadButton from '../MultiUploadButton'

import { BaseText } from 'inside-collection/atoms'
import LoaderUi from '@inside-library/components/ui/LoaderUi'

import GedNavigationMixin from '../mixins/ged-navigation-mixin'

import { storage } from '@inside-library/helpers/Storage'

import { gsap } from 'gsap'

export default {
  name: 'FileNavGed',
  $_i18nRootPath: 'customs.GED.fileNav',
  components: {
    BreadcrumbGed,
    CardGed,
    ListGed,
    HeaderListGed,
    MultiUploadButton,
    BaseText,
    LoaderUi
  },
  mixins: [GedNavigationMixin],
  props: {
    disableToggleDisplay: {
      type: Boolean,
      default: true
    },
    results: {
      type: [Object, Array]
    }
  },
  data() {
    return {
      displayList: false,
      currentData: this.$store.getters.getCurrentFolder || this.heritedData,
      searchData: null,
      isLoading: false
    }
  },
  computed: {
    getFolders() {
      if (!this.isAlive(this.currentData, ['folders', 'data', 0])) {
        return []
      }

      return this.currentData.folders.data.filter(folder => {
        return (
          !folder.is_media_folder ||
          this.getCheckedData(folder, ['brands', 'data'])
            .map(({ uuid }) => uuid)
            .includes(storage.get('brand').uuid)
        )
      })
    },
    getCurrentFolder() {
      return this.$store.getters.getCurrentFolder
    },
    getLoadingGEDStatus() {
      return this.$store.getters.getLoadingGEDStatus
    },
    getGEDSearchStatus() {
      return this.$store.getters.getGEDSearchStatus
    },
    getSearchQuery() {
      if (!this.$store.getters.getSearchList) {
        return
      }

      return this.$store.getters.getSearchList?.ged
    },
    mediaFiles() {
      return this.getCheckedData(this.currentData, [
        this.getCurrentContentType(),
        'data'
      ]).filter(file => this.checkMediaFile(file.file))
    },
    documents() {
      try {
        return this.currentData[this.getCurrentContentType()].data.filter(
          item => (this.isAlive(item, 'status') ? item.status : true)
        )
      } catch {
        return []
      }
    },
    mediaFolderIntro() {
      return this.currentData.media_folder_intro.split('\n').join('<br>')
    },
    allowToAddContents() {
      return this.getCheckedData(this.getUserInfos, 'permissions.add', []).some(
        content => ['folders', 'photos'].includes(content)
      )
    }
  },
  watch: {
    getCurrentFolder(folder) {
      this.bindData(folder)
    },
    results(value) {
      if (this.$store.getters.getSearchList?.ged?.query.length > 2) {
        this.searchData = value
        this.setStoreAction('setGEDSearchStatus', true)
      }
    }
  },
  mounted() {
    this.bindData(this.currentData)

    if (this.getMobile) {
      let bodyRect = document.body.getBoundingClientRect()
      let inputRect = document.querySelector('input').getBoundingClientRect()
      this.targetScroll = inputRect.top - bodyRect.top - inputRect.height - 48

      this.scrollToTarget()
    }
  },
  methods: {
    toggleDisplayList(value) {
      this.displayList = value
    },
    scrollToTarget(y) {
      if (y) {
        TweenLite.to(window, 0.7, { scrollTo: { y: y, x: 0 } })
      } else {
        window.scrollTo(0, 0)
      }
    },
    bindData(folder) {
      if (this.isAlive(folder, ['title'])) {
        if (
          this.isAlive(folder, [
            this.getCurrentContentType('folders'),
            'data'
          ]) &&
          !this.isAlive(folder, [
            this.getCurrentContentType('folders'),
            'data',
            0
          ])
        ) {
          folder[this.getCurrentContentType('folders')].data = []
        }

        if (!folder[this.getCurrentContentType()]) {
          folder[this.getCurrentContentType()].data = []
        }

        this.currentData = folder

        this.scrollToTarget(this.targetScroll)
      }
    },
    checkMediaFile(file) {
      const strings = ['image', 'video']
      const mimetype = this.getCheckedData(file, 'mimetype', '')

      return strings.some(str => mimetype.includes(str))
    }
  }
}
</script>

<style lang="scss">
@use '../../../styles/modules/inside-customs/ged/file-nav.scss' as *;
</style>
