<template lang="pug">
.page--list.f-col.between
    article.f-grow

        header.center.t-up
            .title.f-row
                h3 {{ type }} list
                span(v-if="sortBy")
                    h3 sorted {{ sortBy.replace('-', ' ') }}

            h3(v-if="!loaded") loading...
            .content(
                v-else-if="allPagesLoaded && type && allPages[type]"
                v-html="allPages[type].content"
            )

        ul.posts.f-col(v-if="posts && loaded" :class="{ 'is-grid': grid }")
            li(v-for="(post, i) in posts" :key="post.slug").post.shadow
                card(:content="post" :type="type" :wide="isWide")
        
        //- Important: Do NOT remove this! Required for intersection observer
        footer
            p(v-if="loadingFetched") loading more {{ type }}...
            p(v-if="showMeta") {{ `${type} count: ${Object.values(posts).length}` }}
            p(v-if="showMeta") {{ `show sidebar: ${sidebar}` }}

    sidebar(v-if="sidebar" :type="`${type}`" layout="list")
</template>

<script>
import featuredImage from '@/components/featured-image'
import card from '@/components/card'
import sidebar from '@/components/sidebars/sidebar'
import { postTypeGetters, scrollTop, heroUtils } from './mixin-post-types'

import { postTypes, sortTypes, convertTitleCase, typeFromRoute } from '@/utils/helpers'

const TIMEOUT = 1
const INTERSECT_SELECTOR = '.page--list > article footer'

export default {
    components: { sidebar, featuredImage, card },
    props: {
        sidebar: { type: Boolean },
        grid: { type: Boolean },
        sortBy: { type: String },
    },
    mixins: [postTypeGetters, scrollTop, heroUtils],
    data() {
        return {
            showMeta:false,
            page: 0,
            perPage: 21,
            keepFetching: true,
            loadingFetched: false,
            observer: null
        }
    },
    computed: {
        type() {
            // Checks for type and fixes Episodes route edge case
            return typeFromRoute(this.$route)
        },
        pType() {
            if(!typeFromRoute(this.$route)) return
            return this.sortBy ? `${convertTitleCase(typeFromRoute(this.$route).split('/')[0])}s` : `${convertTitleCase(this.type)}s`
        },
        loaded() {
            if (!this.pType) return
            return this[`all${this.pType}Loaded`]
        },
        posts() {
            if (!this.pType) return
            return this[`all${this.pType}`]
        },
        isWide() {
            return this.type == 'exhibition' || this.type == 'event'
        }
    },
    methods: {
        clearAllPosts() {
            if(!this.type) return console.error(`type: ${this.type}...`)
            const uppercaseType = this.type.toUpperCase() + 'S'
            this.$store.commit(`CLEAR_${uppercaseType}`)
            this.$store.commit(`${uppercaseType}_LOADED`)
        },
        async loadMorePosts() {
            const type = typeFromRoute(this.$route)
            if(!type) return console.warn(`type: ${type} not found...`)
            if(!this.keepFetching) return console.warn('nothing left to fetch...')

            this.loadingFetched = true
            console.warn(`loading page ${this.page + 1} of ${type} posts: ${this.page * this.perPage + 1} to ${(this.page + 1) * this.perPage}`)

            this.page++
            await this.getPosts()
        },
        _getSortBy() {
            return this.sortBy
                ? this.sortBy
                : this.$route.path
                      .split('/')
                      .filter(p => p)
                      .pop()
        },
        _getDispatchParams(perPage) {
            return {
                sortType: this._getSortBy(),
                params: {
                    limit: perPage ? perPage : this.perPage,
                    page: this.page
                }
            }
        },
        async getPosts() {
            let dispatchAction = `getMore${this.pType}`
            let params = this._getDispatchParams()
            
            // For episodes or material sort we grab EVERYTHING
            if(this.type == 'episode' || this.type == 'artist' && this._getSortBy() == sortTypes.material) {
                dispatchAction = `getAll${this.pType}`
                params = this._getDispatchParams(-1)
            }

            const ignore = ['getMorePages']
            let res = null
            if(this.pType && !ignore.includes(dispatchAction) && this.keepFetching) {
                res = await this.$store.dispatch(dispatchAction, params)
            }

            // Stop trying to load more posts
            if(res && !res.length) {
                console.warn(`empty response for ${this.type}:`, res)
                this.keepFetching = false
            }
            this.loadingFetched = false
        },
        // _setHeroInfo(post) {} from mixin
        // _clearHero(store) {} from mixin
        async checkAndSetHero(type) {
            this._clearHero(this.$store)

            await this._getAll('page', this.$store)

            // We always set a hero no matter what
            // Because the hero component will deal
            // with how to render based on hero.url
            if(!this.allPages) return console.warn('no pages in state', this)
            const page = this.allPages.filter(
                page => page.slug == `${type}s`,
            )[0]
            if(!page) return console.warn(`no page for ${type} found`)

            this.$store.commit('SET_HERO', this._setHeroInfo(page))
        },
        setIntersectionLoader() {
            if(!this.type) return console.error('cannot setup intersection handler for undefined type')
            console.log('Setting interesection loader...')
            
            const footerEl = document.querySelector(INTERSECT_SELECTOR)
            if(!footerEl) return

            const onIntersect = (entries, observer) => {
                entries.forEach(entry => {
                    if (!entry.isIntersecting || this.loadingFetched) return
                    setTimeout(() => {
                        this.loadMorePosts()
                    }, TIMEOUT)
                })
            }
            this.observer = new IntersectionObserver(onIntersect, {
                threshold: 0.80
            })
            this.observer['_for_type'] = this.type
            this.observer.observe(footerEl)
        },
        unsetIntersectionLoader() {
            const footerEl = document.querySelector(INTERSECT_SELECTOR)
            if(!footerEl) return

            console.warn('unsetting intersection handler on:', footerEl, this.sortBy)
            this.observer.unobserve(footerEl)
            this.observer.disconnect()
        },
        clearAndInitPostList() {
            this.page = 0
            this.keepFetching = true

            this.checkAndSetHero(this.type)

            // Fires when loading from home
            // Clear any preloaded posts (from home, etc.)
            this.clearAllPosts()
            this.loadMorePosts()
        },
        routeInfoFromPath(fullPath) {
            const [ potentialType, potentialSort ] = fullPath.split('/').filter(e =>  e)
            return {
                sortBy: Object.values(sortTypes).includes(potentialSort) ? potentialSort : null,
                type: postTypes.includes(potentialType) ? potentialType : null
            }
        }
    },
    watch: {
        // This only fires navigating from
        // a list page, to another list page
        type(newType, oldType) {
            if(!postTypes.includes(newType)) return console.warn('type not found...')
        },
        $route(to, from) {
            console.log('---')
            const toPathInfo = this.routeInfoFromPath(to.fullPath)
            const fromPathInfo = this.routeInfoFromPath(from.fullPath)
            console.log('to :', toPathInfo)
            console.log('from :', fromPathInfo)
            
            // Always unset and reset the intersection loader
            this.unsetIntersectionLoader()
            if(!toPathInfo.sortBy != sortTypes.material) {
                this.setIntersectionLoader()
            }

            // Check if we changed sort method
            // from no sort to sorted
            // or sorted to no sort
            // or sort to a different sort(?)
            if(
                from.fullPath.includes(this.sortBy) ||
                (!to.fullPath.includes(this.sortBy) && !from.fullPath.includes(this.sortBy))
            ) {
                const ignore = ['event', 'exhibition', 'post']
                if(ignore.includes(this.type)) return
                console.log('init from $route watch...')
                this.clearAndInitPostList()
            }
        }
    },
    mounted() {
        this.setIntersectionLoader()
        this.clearAndInitPostList()
    },
    beforeDestroy() {
        this.unsetIntersectionLoader()
    }
}
</script>

<style lang="postcss">
// prettier-ignore
@import '../sss/variables.sss'
@import '../sss/theme.sss'
.page--list article
    > header
        padding: 1em
        > h1
            margin: 0
        > .content
            padding: 0
            width: 100%
    > footer
        padding: $ms-0

    /* posts not grid list */
    .posts
        list-style: none
        grid-gap: $ms--2
        .post
            width: 100%

    /* posts in grid list */
    .posts.is-grid
        width: 100%
        display: grid
        grid-template-columns: repeat(1, 1fr)
        align-items: start
        /* This is important for how the grid lines up to the page */
        justify-content: right 
        .post img
            width: 100%

@media (min-width: $medium)
    .page--list
        &.f-col
            flex-direction: row
        > article
            margin: 0 $ms--2 0 0
            .posts.is-grid
                grid-template-columns: repeat(3, 1fr)
</style>
