<template lang="pug">
main.view--chat
    header 
        h2 Chat Page
 
    article(v-if="profile.isLoggedIn && target")
        h3 {{ profile.id }} 
            span chatting with: {{ target.profile_id }}
        p subscriptions: {{ profile.chatter.subscriptions }}

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

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

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

    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)
        },
        getGrouping() {
            return currentProfile.groupings.find(
                g => g.profile.profile_id == this.$route.params.tid,
            )
        },
        sendMessage() {
            const grouping = this.getGrouping()
            currentProfile.chatter.publish(grouping.grouping_name, this.toSend)
            this.toSend = ''
        },
        loadTargetProfile() {
            try {
                const grouping = this.getGrouping()
                if (!grouping) {
                    throw `no match found for ${currentProfile.id.value}`
                }

                this.target = grouping.profile
            } catch (err) {
                console.error(err)
            }
        },
    },
}
</script>
