<template lang="pug">
main.view--home
    header
        h2 home - profile: {{ pid }}
        
    article(v-if="cards.length && !loading")
        ProfileCardList(:profiles="cards" :pid="pid" @reload="getCards")

    p(v-else) Loading...

    MainNav(@show-sidebar="$emit('show-sidebar')")
</template>

<script>
import ProfileCardList from '../components/ProfileCardList.vue'

import { Card } from '../entities'
import { fetchQueueByProfileId } from '../services'
import { mixins } from '../utils'

/** Callback used to format incoming into card */
const convertToCard = profile => {
    if (profile.type !== 'profile') {
        console.error(`Cannot convert ${profile} to Card. Invalid entity.`)
    }
    if (!profile.isValid()) {
        console.warn(`Profile ${profile.profile_id} is not a valid profile.`)
    }
    return new Card({
        pid: profile.profile_id,
        name: profile.user_name,
        avatar: profile.profile_media[0],
    })
}

export default {
    name: 'HomeView',
    components: { ProfileCardList },
    mixins: [mixins.pidMixin, mixins.cardMixin],
    methods: {
        /** Gets called from cardMixin */
        async getCards() {
            this.loading = true
            try {
                const queueList = await fetchQueueByProfileId(this.pid)
                this.cards = this._reformat(queueList, convertToCard)
            } catch (err) {
                console.error(err)
            }
            this.loading = false
        },
    },
}
</script>
