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

  <modal-warning
    :feed_id="modalFeedId"
    :open="warningShow"
    @action="deleteActionModal"
  />

  <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-list-node :feed="feed" @onRemoveFeed="onRemoveFeed"
                      @open-modal="openModal"
      />
    </div>
  </InfinityScroll>
</template>

<script>
import { ref } from 'vue'
import { Inertia } from '@inertiajs/inertia'
import filter from 'lodash/filter'

import FeedListNode from '@/Shared/FeedList/FeedListNode.vue'
import ModalFeed from '@/Shared/Overlay/ModalFeed.vue'
import ModalWarning from '@/Shared/Overlay/ModalWarning.vue'
import InfinityScroll from '@/Shared/Misc/InfinityScroll.vue'

export default {
    components: {
        FeedListNode,
        ModalFeed,
        ModalWarning,
        InfinityScroll,
    },

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

    setup() {
        const containerRef = ref(null)
        return {
            lastNodeLement: containerRef,
        }
    },
    data() {
        return {
            show: false,
            modalFeedId: 0,
            warningShow: false,
            feedLists: [],
            modalFeed: {},
        }
    },

    computed: {
        lastElementID() {
            return this.feedLists[this.feedLists.length - 1]?.id
        },
    },

    mounted() {
        this.feedLists = this.feeds
    },

    methods: {
        putFromPagination(lists) {
            for (let list of lists) {
                this.feedLists.push(list)
            }
        },

        deleteActionModal(removeFeed) {
            if (removeFeed) {
                this.destroyFeed(this.modalFeedId)
            }
            this.warningShow = false
        },

        onRemoveFeed(id) {
            this.warningShow = true
            this.modalFeedId = id
        },
        destroyFeed(id) {
            Inertia.delete(route('feed.destroy', id), {
                preserveScroll: true,
                preserveState: true,
            })

            this.feedLists = filter(this.feedLists, function (x) {
                return x.id !== id
            })
        },

        openModal(feed) {
            this.show = true
            this.modalFeed = feed
        },
        closeModal() {
            this.show = false
        },
    },
}
</script>
