<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 == 'exhibitions' && i > 1 || type == 'events' && 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'

export default {
    components: { sidebar, featuredImage, card },
    props: {
        sidebar: { type: Boolean },
        grid: { type: Boolean },
        sortBy: { type: String }
    },
    mixins: [postTypeGetters, scrollTop],
    computed: {
        type() { // Checks for type and fixes Episodes route edge case 
            return typeFromRoute(this.$route)
        },
        dispatchName() {
            let type = convertTitleCase(this.type)
            return this.sortBy ? `getAll${type.split('/')[0]}` : `getAll${type}`
        },
        loaded() {
            let type = convertTitleCase(this.type)
            if(!type) return
            return this[`all${type}Loaded`]
        },
        posts() {
            let type = convertTitleCase(this.type)
            if(!type) return

            /**
             * We override the API to sort by date
             * because items are returned by ID so
             * we need to re-sort it by date
             */
            let unsortedOfType = Object.values(this[`all${type}`])
            let sortedByRecent = unsortedOfType.sort((postA, postB) => new Date(postB.date) - new Date(postA.date))
            
            /**
             * Sorting of this[`all${type}`] is also controlled by API
             * so if a sortBy is specified we return it sorted or
             * we fail over to sorted by date
             */
            let returnList = sortedByRecent
            if(this.sortBy && sortTypes.includes(this.sortBy)) {
                returnList = this[`all${type}`]
            }
            if(['exhibitions', 'events'].includes(this.type)) {
                returnList = this[`all${type}`]
            }
            return returnList
        },
    },
    methods: {
        getPosts() {
            // Sorting
            let sort = this.sortBy ? this.sortBy : this.$route.path.split('/').pop()
            // !: BUG
            // if(this.type !== sort || !Object.values(sortTypes).includes(sort)) sort = null
            if(Object.values(sortTypes).includes(sort)) {
                console.log('trying to sort by:', sort)
                console.log(`sortTypes includes ${sort}:`, Object.values(sortTypes).includes(sort))
            }
            
            // Don't dispatch if there's no type
            if(this.type && this.dispatchName) {
                this.$store.dispatch(this.dispatchName, sort)
            }
        },
        async checkAndSetHero(type) {
            if(!this['allPagesLoaded']) {
                await this.$store.dispatch('getAllPages')
            }
            const page = this.allPages[type]
            if(!page) return
            
            const json = { url: page.featured, heroType: 'image' }
            if(page.hero && JSON.parse(page.hero) && JSON.parse(page.hero).url) {
                json = JSON.parse(page.hero)
                json.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)
        },
    },
    watch: {
        async $route(to, from){
            // console.log(this.sidebar)
            let type = convertTitleCase(this.type)
            let sort = this.sortBy ? this.sortBy : to.path.split('/').pop()
            this.checkAndSetHero(this.type)
            // console.log('---')
            // console.log(sort)
            if(!this[`all${type}Loaded`] || sort) this.getPosts()
        }
    },
    created() {
        let type = convertTitleCase(this.type)
        console.log(`${type} already loaded?:`, this[`all${type}Loaded`])
        
        this.checkAndSetHero(this.type)
        
        if(!this[`all${type}Loaded`]) this.getPosts()
    }
}
</script>

<style lang="postcss">
@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>