<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")

        .posts(v-if="posts && loaded" :class="{ 'is-grid': grid }")
            section(v-for="(post, i) in posts" :key="post.slug").shadow.post
                card(:content="post" :type="type" :wide="type == 'exhibition' && i > 1 || type == 'event' && i > 1 ")

        footer
            p {{ `${type} count: ${Object.values(posts).length}` }}
            p {{ `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 } from './mixin-post-types'

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

const TIMEOUT = 1

export default {
    components: { sidebar, featuredImage, card },
    props: {
        sidebar: { type: Boolean },
        grid: { type: Boolean },
        sortBy: { type: String },
    },
    mixins: [postTypeGetters, scrollTop],
    data() {
        return {
            page: 1,
            perPage: 9
        }
    },
    computed: {
        type() {
            // Checks for type and fixes Episodes route edge case
            return typeFromRoute(this.$route)
        },
        pType() {
            console.log(this.type, `${convertTitleCase(this.type)}s`)
            return this.sortBy ? `${convertTitleCase(this.type.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}`]
        },
    },
    methods: {
        loadMorePosts() {
            // console.log('loading...')
            this.page++
            this.getPosts(false)
        },
        async getPosts(clear) {
            // Sorting
            let sort = this.sortBy
                ? this.sortBy
                : this.$route.path
                      .split('/')
                      .filter(p => p)
                      .pop()

            const dispatchParams = {
                sortType: sort,
                params: {
                    limit: this.perPage,
                    page: this.page
                }
            }

            const dispatchAction = clear ? `getAll${this.pType}` : `getMore${this.pType}`

            // pType sometimes is undefined so need to dispatch and
            // Episodes only needs load call
            let res = null
            if(this.pType && dispatchAction != `getMoreEpisodes`) {
                res = await this.$store.dispatch(dispatchAction, dispatchParams)
            }

            if(res && !res.length) {
                console.warn('nothing left to get...')
            }
        },
        clearHero() {
            this.$store.commit('SET_HERO', { url: null, heroType: null })
        },
        async checkAndSetHero(type) {
            if (!this['allPagesLoaded']) {
                await this.$store.dispatch('getAllPages', { sortType: null, params: null })
            }

            // 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.log('no pages in state', this)
            const page = this.allPages.filter(
                page => page.slug == type + 's',
            )[0]

            // Clear the hero and bail
            if(!page) return this.clearHero()

            let json = { url: page.featured, heroType:'image' }
            if (
                page.hero &&
                JSON.parse(page.hero) &&
                JSON.parse(page.hero).url
            ) {
                json = JSON.parse(page.hero)
                heson.heroType = 'video'
            }
            // No featured or youTube
            if (!json.url) { json.heroType = null }
            // Set the hero text to the post title or excerpt
            json.text = page && page.excerpt ? page.excerpt : page.title
            this.$store.commit('SET_HERO', json)
        },
        scrollTo(hashtag) {
            setTimeout(() => {
                location.href = hashtag
            }, TIMEOUT)
        },
        setIntersectionLoader() {
            console.warn('setting up intersection handler for:', this.type)
            window.removeEventListener("load", e => {}, false)
            const footerEl = document.querySelector(".footer-wrapper footer")
            if(!footerEl) return

            window.addEventListener("load", e => {
                const observer = new IntersectionObserver(this.loadMorePosts, {
                    rootMargin: "0px 0px -20px 0px",
                })
                observer.observe(footerEl)
            }, false)
        }
    },
    watch: {
        $route(to) {
            // Filter the path to remove blank strings and
            // only grab the hero if moving to another list page
            // eg. list page -> list page
            const path = to.fullPath.split('/').filter(p => p)
            console.log('to:', path)
            console.log('?:', path.pop())
            console.log('?:', path.pop())

            // Always reset the page count
            this.setIntersectionLoader()
            this.page = 1
            
            this.clearHero()
            this.checkAndSetHero(this.type)
            
            // TODO: Track last loaded page per post type
            // Less http calls
            this.getPosts(true)
        },
    },
    mounted() {
        if (this.$route.hash) {
            setTimeout(() => this.scrollTo(this.$route.hash), TIMEOUT)
        }
        this.setIntersectionLoader()
    },
    created() {
        this.checkAndSetHero(this.type)

        // We also need to check if only ONE has been loaded because
        // coming from the homepage there will only be 1 item
        if (!this[`all${this.pType}Loaded`] || this[`all${this.pType}`].length < 2) this.getPosts(true)
    },
}
</script>

<style lang="postcss">
// prettier-ignore
@import '../sss/variables.sss'
@import '../sss/theme.sss'
.page--list
    /* background-color: white */
    article
        > header
            /* padding: 1em 0 1em 0 */
            padding: 1em
            > h1
                margin: 0
            > .content
                padding: 0
                width: 100%
        /* posts not grid list */
        ul
            img
                max-width: 50%

        .is-grid
            display: flex
            flex-direction: row
            flex-wrap: wrap
            justify-content: space-between
            /* extra padding required? */
            /* padding: $ms-0 */
            /* background-color: white */
            section
                width: 32.5%
                /* 4 column grid see how dense this becomes */
                /* width: 24% */
            ul
                flex-wrap: wrap
                list-style: none
                img
                    max-width: 100%
@media (min-width: $medium)
    .page--list.f-col
        flex-direction: row
</style>
