<template lang="pug">
.page--single.f-row.between
    article(v-if="post").f-grow.shadow
        header
            h1 {{ type }}:{{ $route.params.slug }} {{ post.title }}
            p(v-if="post.categories") categories: {{ post.categories }}
            p(v-if="post.type") type: {{ post.type }}
            .date-info(v-if="type === 'events' || post.type === 'exhibitions'")
                p start: {{ dateFrom(post.start) }}
                p end: {{ dateFrom(post.end) }}


        .post-single.block-wrapper(v-for="(block, i) in post.blocks" :key="`block-${i}`")
            //- ?: are objects are always gallery blocks
            .gallery.block(v-if="typeof block === 'object'" :class="`gallery-${i}`")
                p gallery number: {{ i }}
                ul.t-cntr 
                    li(v-for="(imageID, j) in post.galleries[block.gallery].ids" :class="`gallery-${i}--image-${j+1}`" :key="`block-${i}-${j}`")
                        img(@click="openGallery(i - 1, imageID)" :src="post.attached[imageID]['thumbnail']")
                        //- TO DO Caption stuff and full screen Title/Description
                        p Caption goes here<br>
                            button(@click="openGallery(i - 1, imageID)") gallery: {{ i }} image: {{ imageID }}
                        br
                //- Fullscreen gallery component for every gallery block
                gallery(
                    v-if="activeGalleryIndex == (i - 1)"
                    :activeImageIndex="activeImageIndex"
                    v-on:close="activeGalleryIndex = -1"
                    :images="imagesInGallery"
                )

            //- Just a regular block (html or img)
            .block(v-else v-html="block")

    sidebar(v-if="sidebar" :type="`${type}`")
        .shadow
            h1.t-up single slot
            div
                p body whatever
</template>

<script>
import sidebar from '@/components/sidebars/sidebar'
import gallery from '@/components/gallery/'
import { postTypeGetters } from './mixin-post-types'

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

export default {
    components: { sidebar, gallery },
    props: {
        sidebar: { type: Boolean }
    },
    mixins: [postTypeGetters],
    data() {
        return {
            // Gallery control
            activeGalleryIndex: -1,
            activeImageID: -1
        }
    },
    computed: {
        type() { // Checks for type and fixes Episodes route edge case 
            return typeFromRoute(this.$route)
        },
        /**
         * We get the actual post data using the slug
         */
        post() {
            return this.posts[this.$route.params.slug]
        },
        /**
         * We grab posts using the type derived from
         * the route (See typeFromRoute() helper) and
         * create a map keyed by post slug 
         */
        posts() {
            let type = convertTitleCase(this.type)
            
            if(!type) return []
            
            // Return list keyed by slug
            return Object.values(this[`all${type}`]).reduce((postsMap, post) => { 
                postsMap[post.slug] = post
                return postsMap
            }, {})
        },

        /**
         * We need a convenient way to get all the images
         * broken down by gallery. We use the active gallery
         * image IDs to create a map. We match the ID to the
         * image size and url information returned by post.attached
         */
        imagesInGallery() {
            if(!this.activeGalleryIndex < 0) return {}
            // Create a map of images by their ID
            // {
            //     imageId: { 'thumbnail': url, 'large': url }
            // }
            return this.post.galleries[this.activeGalleryIndex].ids.reduce((imageMap, id) => {
                imageMap[id] = this.post.attached[id]
                return imageMap
            }, {})
        },
        activeImageIndex() {
            return Object.keys(this.imagesInGallery).indexOf(this.activeImageID.toString())
        }
    },
    methods: {
        /**
         * We set the active gallery to the index.
         * Everything kicks off when activeGallery
         * is set. We also need to set the activeImageID
         * to the image clicked
         * @param {number} galleryIndex
         * @param {string} imageID 
         */
        openGallery(galleryIndex, imageID) {
            this.activeGalleryIndex = galleryIndex
            this.activeImageID = imageID ? imageID : 0
        },

        /**
         * Everytime the posts object changes
         * we use this to set a new HERO
         * in vuex
         * @param {object} posts 
         */
        checkAndSetHero(posts) {
            const post = posts[this.$route.params.slug]
            if(!post || !post.hero) return

            const json = JSON.parse(post.hero)
            this.$store.commit('SET_HERO', json)
        },

        /**
         * Date Object from unix strings from db
         */
        dateFrom(unix) {
            return new Date( parseInt(unix) * 1000 )
        },
    },
    watch: {
        posts(newVal, oldVal) {
            this.checkAndSetHero(newVal)
        }
    },
    created() {
        /**
         * Conditionally load based on post type
         * which is derived from the route
         * !: posts watcher fires when this finishes
         */
        let type = convertTitleCase(this.type)
        if(!this[`all${type}Loaded`] && type) {
            // console.log('Retrieving...', type)
            this.$store.dispatch(`getAll${type}`)
        }
    }
}
</script>

<style lang="postcss">
.page--single
    article
        ul
            list-style: none
            li
                img
                    width: 100%
</style>