<template lang="pug">
.page--list.f-row.between
    article.f-grow
        header.f-col.center.t-up
            .title.f-row
                h1 {{ type }} list
                span(v-if="sortBy")
                    h1 &nbsp;sorted by {{ 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 in posts" :key="post.slug").shadow.post
                header
                    router-link(:to="`/${type}/${post.slug}`")
                        featured-image(:post="post")
                        h2.t-up {{ post.title }}
                article
                    h4 {{ post.date }}
                    p Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eu elit in ex pharetra volutpat ac at magna. Duis libero est, imperdiet non sollicitudin vel, eleifend at ante...

        footer
            p {{ `${type} count: ${Object.values(posts).length}` }}
            p {{ `show sidebar: ${sidebar}` }}
        
    sidebar(v-if="sidebar" :type="`${type}`")
        .shadow
            h1.t-up slots stuff
            div
                p more body whatever
                p another line of stuff
</template>

<script>
import featuredImage from '@/components/featured-image'
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 },
    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 resort 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
             */
            return this.sortBy ? this[`all${type}`] : sortedByRecent
        },
    },
    methods: {
        getPosts() {
            // Sorting
            let sort = this.sortBy ? this.sortBy : this.$route.path.split('/').pop()
            if(Object.values(sortTypes).includes(sort)) {
                console.log('trying to sort by:', sort)
                console.log(`sortTypes includes ${sort}:`, Object.values(sortTypes).includes(sort))
            }
            // Is this a sort type?
            // !: BUG
            // if(this.type !== sort || !Object.values(sortTypes).includes(sort)) sort = null
            
            // 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
            let 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'
            }
            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)
            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)
        console.log(this.$store)
        if(!this[`all${type}Loaded`]) this.getPosts()
    }
}
</script>

<style lang="postcss">
.page--list
    article
        > header
            padding: 1em 0 1em 0
            > h1
                margin: 0
            > .content
                padding: 0
                width: 100%
        /* posts not grid list */
        ul
            img
                max-width: 50%
            li
                
        .is-grid
            display: flex
            flex-direction: row
            flex-wrap: wrap
            section
                width: 33%
            ul
                flex-wrap: wrap
                list-style: none
                img
                    max-width: 100%
                
</style>