<template lang="pug">
// TODO: Add router link to OnboardingView.vue's survey
main.view--home
    article.w-flex.sm-column.md-row.align-center
        template(v-if='isLoading')
            w-spinner(bounce)

        template(v-else-if='!isLoading && cards.length > 0')
            ProfileCardList(:cards='cards' @loadMore='onLoadMore')

        template(v-else-if='cards.length === 0')
            p No profiles in match_queue.
    MainNav
</template>

<script>
import 'wave-ui/dist/wave-ui.css'
import ProfileCardList from '../components/ProfileCardList.vue'
import AspectBar from '../components/AspectBar.vue'
import SummaryBar from '../components/SummaryBar.vue'
import PairingButton from '../components/PairingButton.vue'

import { Card } from '../entities'

import { currentProfile, fetchQueueByProfileId } from '../services'
import { mixins } from '../utils'

const notificationOpts = {
    message: null,
    timeout: 6000,
    bgColor: 'white',
    color: 'success',
    dismiss: false,
    shadow: true,
    round: true,
    sm: true,
    icon: 'wi-star',
}

/** 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,
        AspectBar,
        SummaryBar,
        PairingButton,
    },
    mixins: [mixins.profileMixin],
    data() {
        return {
            fetchedCards: [],
            offset: 0,
        }
    },
    computed: {
        cP() {
            return currentProfile ? currentProfile : null
        },
        cards() {
            let initialCards = currentProfile.queue.map(qProfile =>
                convertToCard(qProfile),
            )
            if (this.fetchedCards.length === 0) return initialCards
            return [
                ...initialCards,
                ...this.fetchedCards.map(qProfile => convertToCard(qProfile)),
            ]
        },
    },
    methods: {
        async onLoadMore() {
            this.offset += 5 // fetch next batch with updated offset
            let newQueue = await fetchQueueByProfileId(
                currentProfile.id._value,
                this.offset,
            )
            this.fetchedCards.push(...newQueue) // update fetchedCards => recalculate cards
        },
        // this can be placed in utils/notification.js
        notify(payload) {
            notificationOpts.message = payload
            this.$waveui.notify(notificationOpts)
        },
    },
}
</script>
