<script>
import moment from 'moment'

import HorizontalLayouts from '@inside-layouts/displays/HorizontalLayouts'
import CloseFlashInfoCustoms from './../../inside-customs/components/modals/sub-components/CloseFlashInfoCustoms'

import { getModalFields } from '@inside-library/helpers/ContentConfHelper.js'
import { http } from '@inside-library/helpers/Http'

export default {
  name: 'horizontal-layouts',
  extends: HorizontalLayouts,
  data() {
    return {
      flashInfoNews: null,
      popinInfo: null,
      reactionDate: null
    }
  },
  watch: {
    popinInfo(showPopin) {
      if (!showPopin || moment(this.reactionDate).isSame(moment())) return

      this.openModal()
    },
    getUserInfos(userInfos) {
      if (userInfos) {
        this.fetchPopin()
      }
    }
  },
  mounted() {
    if (this.getUserInfos) {
      this.fetchPopin()
    }
  },
  methods: {
    async fetchPopin() {
      try {
        const { popin, reaction_date: reactionDate } = await http.get('popin')

        this.popinInfo = popin
        this.reactionDate = reactionDate
      } catch (err) {
        throw new Error(err)
      }
    },
    modalCallback() {
      try {
        http.post('reaction/popin', {
          uuid: this.flashInfoNews.uuid
        })
      } catch (err) {
        throw new Error(err)
      }
    },
    async openModal() {
      try {
        const { data } = await http.get('content/news', {
          fields: getModalFields('news', this.$_currentLang),
          filters: {
            sort: 'published_at:desc',
            'is_flash:eq': true,
            limit: 1,
            langcode: this.$_currentLang,
            status: 1
          }
        })

        this.flashInfoNews = data[0]

        this.triggerModal(
          'flash-info',
          'static',
          { item: data[0], callback: this.modalCallback },
          {
            layout: 'center',
            width: '60%',
            transition: 'fadeInLeft',
            closeComponent: CloseFlashInfoCustoms
          }
        )
      } catch (err) {
        throw new Error(err)
      }
    }
  }
}
</script>
