<template lang="pug">
.page--single.f-row.between
    gallery(v-if="activeGalleryIndex >= 0" :activeImageIndex="activeImageIndex" :images="imagesInGallery" @close="closeGallery")

    article(v-if="!post")
        header
            p loading...
    article(v-else).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 }}
            p(v-if="post.subtypes") subtypes: {{ post.subtypes }}

            .date-info(v-if="type === 'events' || post.type === 'exhibitions'")
                p start: {{ dateFrom(post.start) }}
                p end: {{ dateFrom(post.end) }}

        ul
            li(v-for="(block, index) in post.blocks" :key="`block-${index}`" class="post-single block-wrapper")
                block(:block="block" @open-gallery="openGallery")

        //- related artists section example layout
        section(v-if="type === 'episodes' && post" :post="post")
            h2.t-up featured in this episode
            ul.f-row.between
                img(src="https://i1.wp.com/www.craftinamerica.org/wp-content/uploads/2020/09/20200210_133120-e1599254267307.jpg")
                li.f-col.between
                    h2.t-up Julie Schafler Dale
                    p Julie Schafler Dale was the founder and President of Julie: Artisans’ Gallery, New York, which conducted business on Madison Avenue for over forty years. She has served on the Advisory Council for The...
            ul.f-row.between
                img(src="https://i1.wp.com/www.craftinamerica.org/wp-content/uploads/2020/09/P1033899.jpg")
                li.f-col.between
                    h2.t-up George Rodriguez
                    p George Rodriguez is a Seattle-based ceramic artist and sculptor who, throughout his career, has used oversized ceramic personalities he creates to tell universal stories. He was born and raised in El Paso, where...

        credits(v-if="type === 'episodes' && post" :post="post")

    sidebar(v-if="sidebar" :type="`${type}`" layout="single" :related="p2pPostsByType")

</template>

<script>
import sidebar from '@/components/sidebars/sidebar'
import gallery from '@/components/gallery/'
import block from '@/components/content-block/block'
// import artists from '@/components/artist'
import credits from '@/components/credits'

import { postTypeGetters, scrollTop } from './mixin-post-types'

import { convertTitleCase, dePluralize, typeFromRoute } from '@/utils/helpers'
 
export default {
    components: { sidebar, gallery, block, credits },
    props: {
        sidebar: { type: Boolean },
        id: { type: Number }
    },
    mixins: [postTypeGetters, scrollTop],
    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() {
            if(!this[this.type]) return

            const type = dePluralize(this.type)

            // State not a getter!
            const singleOfTypeFromState = this[this.type][`single${convertTitleCase(type)}`]

            if(!singleOfTypeFromState) return

            return singleOfTypeFromState
        },

        idsForGallery() {
            if(!this.post || this.activeGalleryIndex < 0) return []
            return this.post.galleries[this.activeGalleryIndex].ids
        },
        /**
         * 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 {}

            return this.idsForGallery.reduce((imageMap, id) => {
                imageMap[id] = this.post.attached[parseInt(id)]
                return imageMap
            }, {})
        },
        activeImageIndex() {
            return Object.keys(this.imagesInGallery).indexOf(this.activeImageID.toString())
        },
        p2pPostsByType() {
            return this.post ? Object.values(this.post.relatedto).reduce((byType, relatedPost) => {
                if(!byType[relatedPost.type]) byType[relatedPost.type] = []
                byType[relatedPost.type].push(relatedPost)
                return byType
            }, {}) : {}
        }
    },
    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 {string} imageInfo
         */
        openGallery(imageInfo) {
            const byIndex = this.post.galleries.reduce((byIndex, gallery, index) => {
                byIndex[index] = gallery.ids
                return byIndex
            }, {})
            let matchingIndex = 0
            Object.keys(byIndex).forEach(galleryIndex => {
                if(byIndex[galleryIndex].includes(parseInt(imageInfo.dataset.id))) matchingIndex = galleryIndex
            })
            this.activeGalleryIndex = matchingIndex
            this.activeImageID = imageInfo.dataset.id ? parseInt(imageInfo.dataset.id) : parseInt(imageInfo.className.split('-').pop())
        },
        closeGallery() {
            this.activeGalleryIndex = -1
            this.activeImageID = -1
        },
        /**
         * Everytime the posts object changes
         * we use this to set a new HERO
         * in vuex
         * @param {object} posts
         */
        checkAndSetHero(post) {
            if(!post) return
            const json = { url: post.featured, heroType: 'image' }
            if(post.hero && JSON.parse(post.hero).url) {
                json = JSON.parse(post.hero)
                json.heroType = 'video'
            }
            this.$store.commit('SET_HERO', json)
        },

        /**
         * Date Object from unix strings from db
         */
        dateFrom(unix) {
            return new Date( parseInt(unix) * 1000 )
        },

        async loadPostData() {
            /**
             * 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.$store.state[this.type]) return 

            let allPostsOfType = this.$store.state[this.type].all

            /**
             * Load posts if they're not already in state
             */
            if(!this[`all${type}Loaded`] && allPostsOfType.length < 1) {
                const res = await this.$store.dispatch(`getAll${type}`)
                allPostsOfType = res
                // console.log(`reloaded ${type}...`)
            }

            if(Object.values(allPostsOfType).length < 1) return
            const singlePostData = Object.values(allPostsOfType).filter(post => post.slug == this.$route.params.slug)[0]

            if(!singlePostData) return

            await this.$store.dispatch(`getSingle${dePluralize(type)}`, singlePostData.id)
        }
    },
    watch: {
        post(newVal, oldVal) {
            this.checkAndSetHero(newVal)
        },
        $route(newVal, oldVal) {
            this.loadPostData()
        }
    },
    async created() {
        this.loadPostData()
    }
}
</script>

<style lang="postcss">
@import '../sss/variables.sss'
@import '../sss/theme.sss'
.page--single
    article
        ul
            grid-gap: $ms-0
            list-style: none
            img
                width: 50%
            li
        /* responsive iframe embeds */
        /* .iframe-container 
            position: relative
            width: 100% 
            padding-bottom: 56.25% 

        .iframe-container iframe 
            position: absolute 
            top: 0px 
            left: 0px 
            width: 100% 
            height: 100%  */

    @media (--large-viewport)
        .sidebar
            background-color: purple

</style>