<template lang="pug">
main.view--matches.f-col.start.w-full
    header
        h2 Matches

    article(v-if='matches.length && !loading')
        ProfileCardList(:pid='pid' :profiles='matches' @reload='getCards')

    p(v-else-if='matches.length === 0') No matches.
    p(v-else) Loading...

    MainNav
</template>

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

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

/** Callback used to format incoming into card */
const convertToCard = 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: 'MatchView',
    components: { ProfileCardList },
    mixins: [mixins.pidMixin, mixins.cardMixin],
    methods: {
        /** Gets called from cardMixin */
        async getCards() {
            this.loading = true
            try {
                const matchList = await fetchMembershipsByProfileId(this.pid)
                this.cards = this._reformat(matchList, convertToCard)
            } catch (err) {
                console.error(err)
            }
            this.loading = false
        },
    },
}
</script>
