<template>
  <modal-feed
    :modal-feed="modalFeed"
    :open="show"
    @close-modal="closeModal"
    @destroyFeed="destroyFeed"
  />

  <InfinityScroll :node-element="lastNodeLement" :next-cursor="nextCursor"
                  @fromPagination="putFromPagination"
  >
    <div v-for="feed in feedLists" :key="feed.id"
         :ref="el => { if (el && feed.id === lastElementID) lastNodeLement = el }"
    >
      <feed-node :feed="feed" @open-modal="openModal" />
    </div>
  </InfinityScroll>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { Inertia } from '@inertiajs/inertia'
import findIndex from 'lodash/findIndex'

import FeedNode from '@/Shared/Feed/FeedNode.vue'
import ModalFeed from '@/Shared/Overlay/ModalFeed.vue'
import InfinityScroll from '@/Shared/Misc/InfinityScroll.vue'


export default {
    components: {
        FeedNode,
        ModalFeed,
        InfinityScroll,
    },

    props: {
        feeds: Array,
        nextCursor: { type: String, default: '' },
    },

    setup(props) {
        let feedLists = ref(props.feeds)

        const show = ref(false)
        const modalFeed = ref({})

        const containerRef = ref(null)

        const lastElementID = computed(
            () => feedLists.value[feedLists.value.length - 1]?.id
        )

        watch(props, (props) => {
            feedLists.value = props.feeds
        })

        const putFromPagination = (lists) => {
            for (let list of lists) {
                feedLists.value.push(list)
            }
        }

        const destroyFeed = () => {
            Inertia.delete(route('feed.destroy', modalFeed.value.id), {
                preserveScroll: true,
                preserveState: true,
            })
            const index = findIndex(
                feedLists.value,
                (item) => item.id === modalFeed.value.id
            )
            feedLists.value.splice(index, 1)
        }

        const openModal = (feed) => {
            show.value = true
            modalFeed.value = feed
        }
        const closeModal = () => {
            show.value = false
        }

        return {
            lastNodeLement: containerRef,
            openModal,
            closeModal,
            destroyFeed,
            lastElementID,
            show,
            modalFeed,
            feedLists,
            putFromPagination,
        }
    },
}
</script>
