<template lang="pug">
main.view--chat
    header(v-if='profile')
        p {{ profile.chatter }}
        hr
        p messages: {{ messages }}
        hr
        p subscriptions: {{ profile.chatter.subscriptions }}

    article(v-if='profile.isLoggedIn && target')
        h3 {{ profile.id }}&nbsp;
            span chatting with: {{ target.profile_id }}

        ul#messages.w-flex.column
            //- li.pa1(v-for='(message, i in messages)')
            //-     w-card.w-flex.row
            //-         article
                //- p {{ message.message }}
        //-             footer
        //-                 p {{ message.publisher }} | {{ message.timetoken }}
        //-                 w-button.my12(@click='openDrawer = i' text) setting
        //-             w-drawer(absolute v-model='openDrawer' width='160px')
        //-                 p some settings things

        input(@keyup.enter='sendMessage' v-model='toSend')
        button(@click='sendMessage') send

    p(v-else-if='profile.isLoggedIn && !target') No match found between profile {{ $route.params.pid }} and {{ profile.id }}...
    w-spinner(bounce v-else)

    MainNav
</template>

<script>
import { currentProfile } from '../services'

export default {
    name: 'ProfileView',
    data: () => ({
        target: null,
        toSend: '',
        messages: [],
        openDrawer: null,
    }),
    computed: {
        profile: () => currentProfile,
    },
    watch: {
        profile() {
            this.loadTargetProfile()
            currentProfile.chatter.setOnMessage(this._onMessage)
        },
    },
    created() {
        this.loadTargetProfile()
        currentProfile.chatter.setOnMessage(this._onMessage)
    },
    methods: {
        /**
         * Pubnub message callback fires when message event
         * is detected. We define is HERE because we need the
         * component state and `this` context
         */
        _onMessage(e) {
            if (!e.message) return
            this.messages.push(e)
        },
        // TODO: test this
        getGrouping() {
            return currentProfile.groupings.find(
                g => g.profile.profile_id == this.$route.params.pid,
            )
        },
        sendMessage() {
            const grouping = this.getGrouping()
            currentProfile.chatter.publish(grouping.grouping_name, this.toSend)
            this.toSend = ''
        },
        // TODO: test this
        loadTargetProfile() {
            try {
                const grouping = this.getGrouping()
                if (!grouping) {
                    throw `no match found for ${currentProfile.id.value}`
                }
                console.log('grouping :', grouping)
                this.target = grouping.profile
            } catch (err) {
                console.error(err)
            }
        },
    },
}
</script>
