<template lang="pug">
.page--list.f-row.between
    article.f-grow
        header.f-row.center.t-up
            h1 {{ type }} list
            span(v-if="sortBy")
                h1 &nbsp;sorted by {{ sortBy.replace('-', ' ') }}

        .posts(:class="{ 'is-grid': grid }")
            section(v-for="post in posts" :key="post.slug").shadow.post
                router-link(:to="`/${type}/${post.slug}`")
                    p {{post.featured}}
                    ul.f-row
                        img(v-if="post.featured" :src="post.featured" alt="post thumbnail")
                        img(v-else-if="post.hero && JSON.parse(post.hero).url" :src="getThumbnailFromYt(JSON.parse(post.hero).url)" alt="post thumbnail from YouTube")
                        p(v-else-if="post.hero") ERROR: {{ post.hero }}
                        p(v-else) ERROR: no thumbnail
                        li.f-col.between
                            h2.t-up {{ post.title }}
                            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...

        //- posts not grid
        
        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 sidebar from '@/components/sidebars/sidebar'
import { postTypeGetters, scrollTop } from './mixin-post-types'

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

export default {
    components: { sidebar },
    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}`
        },
        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: {
        getThumbnailFromYt(url) {
            return ytThumbnail(url, 'medium')
        },
        setHeroAndGetPosts() {
            let type = convertTitleCase(this.type)
            
            // 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?
            if(this.type !== sort || !Object.values(sortTypes).includes(sort)) sort = null
            
            // Don't dispatch if there's no type
            if(this.type) {
                this.$store.dispatch(this.dispatchName, sort)
            }
            
            if(this.$store.state.hero.url !== type) this.$store.commit('SET_HERO', type)
        }
    },
    watch: {
        $route(to, from){
            let type = convertTitleCase(this.type)
            let sort = this.sortBy ? this.sortBy : to.path.split('/').pop()
            
            if(!this[`all${type}Loaded`] || sort) this.setHeroAndGetPosts()
        }
    },
    created() {
        let type = convertTitleCase(this.type)
        // console.log('already loaded ?:', this[`all${type}Loaded`])
        
        if(!this[`all${type}Loaded`]) this.setHeroAndGetPosts()
    }
}
</script>

<style lang="postcss">
.page--list
    article
        /* 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>