<template>
  <div class="paragraph paragraph-file">
    <a class="paragraph-file__container">
      <div class="paragraph-file__container--left" @click="handleClick">
        <Icon
          v-if="!isBookmarkRoute"
          :color="$_theme('colorSecondary900')"
          :aria-label="$_tr('altIconFile')"
          :icon="
            getIcoExtension() === 'doc' ? 'file' : `${getIcoExtension()}-file`
          "
          size="l"
        />

        <Icon
          v-else
          :color="$_theme('colorSecondary900')"
          :aria-label="$_tr('altIconArrowLink')"
          icon="arrow-link"
          size="m"
        />

        <div>
          <Title tag="h5">
            {{
              unescapeHtml(
                currentData.title ||
                  $_getFilename(currentData.file || currentData)
              )
            }}
          </Title>

          <div class="paragraph-file__infos">
            <BaseText
              v-if="getCheckedData(currentData, ['file', 'size']) && !isBookmarkRoute"
              class="paragraph-file__weight"
            >
              {{ getFileSize(currentData.file.size) }}
            </BaseText>

            <BaseText
              v-else-if="currentData.published_at || currentData.created_at"
            >
              {{
                $_formatDate(currentData.published_at || currentData.created_at)
              }}
            </BaseText>

            <BaseText
              v-if="currentData.description"
              class="paragraph-file__descr"
            >
              {{ currentData.description }}
            </BaseText>
          </div>
        </div>
      </div>

      <div class="paragraph-file__container--right">
        <div class="cart">
          <transition name="fadeIn" mode="out-in">
            <svg
              v-if="!alreadyReacted && !isActive && !isCartRoute && !isBookmarkRoute"
              v-html="basketDecoded"
              width="24"
              height="24"
              @click="setReaction"
            />

            <Icon
              v-else-if="isCartRoute || isBookmarkRoute"
              :aria-label="$_tr('altIconClose')"
              icon="close"
              class="sid2-more"
              @click="unsubToReaction"
            />
          </transition>
        </div>

        <Icon
          v-if="!isBookmarkRoute"
          :aria-label="$_tr('altIconDownload')"
          icon="download"
          @click="
            downloadFile(currentData.file ? currentData : { file: currentData })
          "
        />
      </div>
    </a>
  </div>
</template>

<script>
import { http } from '@inside-library/helpers/Http'
import { formatHref } from '@inside-library/helpers/Langs'
import { unescapeHtml } from '@inside-library/filters/UnescapeHtml'

import { Icon, BaseText, Title } from 'inside-collection/atoms'
import FileParagraph from '@inside-library/components/paragraphs/FileParagraph'

import ReactionMixin from '@inside-library/mixins/reaction-mixin'

import basket from '@inside-customs/assets/icons-v2/basket.svg'

export default {
  name: 'FileParagraph',
  $_i18nRootPath: 'overrides.paragraphs.file',
  components: {
    Icon,
    BaseText,
    Title
  },
  extends: FileParagraph,
  mixins: [ReactionMixin],
  data() {
    return {
      currentData: this.heritedData.file,
      basketDecoded: decodeURIComponent(
        basket.replace('data:image/svg+xml,', '')
      )
    }
  },
  computed: {
    isCartRoute() {
      return this.$route.name.includes('Cart')
    },
    isBookmarkRoute() {
      return this.$route.name.includes('Bookmarks')
    },
    reactionType() {
      if (this.isBookmarkRoute) return 'bookmark'

      return 'basket'
    },
    alreadyReacted() {
      let hasReacted = false

      if (
        this.getCheckedData(this.currentData, [
          'reactions',
          'data',
          this.reactionType
        ])
      ) {
        hasReacted = this.getCheckedData(this.currentData, [
          'reactions',
          'data',
          this.reactionType
        ]).find(item => {
          return (
            this.getCheckedData(item, ['users', 'uuid']) ===
            this.getUserInfos.uuid
          )
        })
      }
      return hasReacted
    },
    deletionInProgress() {
      return this.$store.getters.getDeletionCartStatus
    }
  },
  watch: {
    isActive() {
      this.$_triggerSuccessToast({
        text: this.$_tr('customs.CART.added')
      })
    }
  },
  methods: {
    unescapeHtml,
    async handleClick() {
      if (this.isBookmarkRoute && this.currentData.content_type) {
        this.$store.commit(
          'setCurrentModalContentType',
          this.currentData.content_type
        )

        const method = this.$_getRedirectionMethod(
          this.currentData.content_type
        )
        const redirection = await method({ data: this.currentData })

        if (redirection) {
          this.$router.push(formatHref(redirection, this.$_currentLang))
        }
      } else {
        this.downloadFile(
          this.currentData.file ? this.currentData : { file: this.currentData }
        )
      }
    },
    setReaction() {
      this.sendReaction({
        type: this.reactionType,
        relatedUuid: this.currentData.uuid,
        relatedType: this.heritedData.contentType,
        domain: this.heritedData.domain
      })
    },
    async sendReaction({ type, relatedUuid, relatedType, domain }) {
      try {
        await http.post('reactions', {
          type: type,
          user_uuid: this.getUserInfos.uuid,
          related_uuid: relatedUuid,
          related_type: relatedType,
          domain: domain,
          langcode: this.$_currentLang,
          fields: JSON.stringify(['count'])
        })

        this.isActive = true

        this.$store.commit('updateCartCounter')
      } catch (err) {
        throw new Error(err)
      }
    },
    unsubToReaction() {
      if (!this.deletionInProgress) {
        this.$store.commit('setDeletionCartStatus', true)

        this.delete(
          `reactions/${this.reactionType}/${this.currentData.uuid}/${this.getUserInfos.uuid}/${this.$_currentLang}`
        ).then(res => {
          if (res.status === 200) {
            this.$emit('removeDocument', this.currentData)

            if (this.isCartRoute) {
              this.$store.commit('updateCartCounter', { remove: true, sum: 1 })
            }

            this.$store.commit('setDeletionCartStatus', false)
            this.isActive = false
          }
        })
      }
    }
  }
}
</script>

<style lang="scss">
.paragraph-file {
  &__container--left .ds-icon-container {
    margin-right: var(--spacing-m);
  }

  .cart {
    margin-right: var(--spacing-s);
    height: 2.3rem;
  }

  .cart,
  i {
    cursor: pointer;
    line-height: 2.3rem;
  }

  .cart .more {
    cursor: pointer;
    display: block;
    height: inherit;
    font-weight: bold;
    transition: all 0.3s ease;
    transform: rotate(45deg);

    &:hover {
      transform: rotate(135deg);
    }
  }
}

.inside-radius {
  .paragraph-file {
    &__container {
      border-radius: var(--radius-m);
    }
  }
}
</style>
