<template lang="pug">
main.view--home(style="display:flex; flex-direction:column; gap: 40px")
    div.view--nav(style="display: flex; justify-content: space-between;")
        header
            h2 home - profile: {{ pid }}
        w-drawer(v-model="openDrawer")
        w-button(@click="openDrawer = true" outline="")
            | Active Chats
  
    h2 Match Queue
    article(v-if="cards.length && !loading")
        ProfileCardList(:profiles="cards" :pid="pid" @reload="getCards")

    p(v-else) Loading...

    h2 Matches
    article(v-if="matches.length && !loading")
        ProfileCardList(:profiles="matches" :pid="pid" @reload="getCards")
    
    p(v-else-if="matches.length===0") No matches.
    p(v-else) Loading...

</template>

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

import { Card } from '../entities'
import { fetchQueueByProfileId, fetchMembershipsByProfileId } 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],
    })
}

const converGroupingToCard = grouping => {
    if (grouping.type !== 'grouping') {
        console.error(`Cannot convert ${grouping} to Card. Invalid entity.`)
    }
    if (!grouping.profile.isValid()) {
        console.warn(`Profile in ${grouping} is not a valid profile.`)
    }
    return new Card({
        pid: grouping.profile.profile_id,
        name: grouping.profile.user_name,
        avatar: grouping.profile.profile_media[0],
    })
}

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