<template lang="pug">
main.view--chat
    header.mb6(v-if='profile && grouping')
        h3 chatting with:
        span {{ target.profile_id }} |
        span(v-if='grouping.revealedFromNotification.length')
            span(v-for='revealed in grouping.revealedFromNotification')
                span(v-if='revealed.profile_id === target.profile_id')
                    span {{ revealed[revealed.tag_description] }} |
        span(v-else)
            span {{ grouping.profile.user_name }} | {{ grouping.profile.user_email }}
        h3 logged in as:
        p {{ profile.id }} | {{ profile._profile.user_name }} | {{ profile._profile.user_email }}
        //- p subscriptions: {{ profile.chatter.subscriptions }}
        hr

        .w-flex.column(v-if='!grouping._loading')
            .w-flex.row
                button(@click='reveal(7)') reveal my name
                button(@click='reveal(8)') reveal my email
                // TODO: Remove later, only for testing
                button(@click='checkData()') check data
            span(v-if='grouping.revealed[profile.id.value]')
                p you revealed:
                ul(
                    v-for='reveal in [...new Set(grouping.revealed[profile.id.value])]'
                )
                    li {{ reveal.description }}
            span(v-if='grouping.revealed[target.profile_id]')
                p they revealed:
                ul(v-for='reveal in grouping.revealed[target.profile_id]')
                    li {{ reveal.description }}: {{ target[reveal.description] }}
            span(v-if='grouping.revealedFromNotification.length')
                p recently revealed:
                ul(v-for='revealed in grouping.revealedFromNotification')
                    li(
                        v-if='revealed[revealed.tag_description] !== profile._profile[revealed.tag_description]'
                    ) {{ revealed.tag_description }}: {{ revealed[revealed.tag_description] }}

    article
        template(v-if='isLoading')
            w-spinner(bounce)

        template(v-if='!isLoading && target')
            ul#messages.w-flex.column
                template(v-for='chatmessage in messages')
                    li(
                        :class='[{ me: chatmessage.publisher == profile.id.value }, chatmessage.publisher]'
                        v-if='chatmessage.message && chatmessage.message.description'
                    )
                        ChatBubble(
                            :message='chatmessage.message.description'
                            :publisher-id='chatmessage.publisher'
                            :time='chatmessage.timetoken'
                        )

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

    footer.w-flex.row
        w-input(@keyup.enter='sendMessage' outline v-model='toSend')
        w-button(@click='sendMessage')
            w-icon.icon-paper-plane

    MainNav
</template>

<script lang="js">
import ChatBubble from '../components/ChatBubble.vue'
import { currentProfile } from '../services'
import { mixins } from '../utils'

export default {
    name: 'ProfileView',
    components: { ChatBubble },
    mixins: [mixins.profileMixin],
    data: () => ({
        target: null,
        toSend: '',
        messages: [],
        grouping: {},
        them: {},
    }),
    computed: {
        theyRevealed() {
            return this.them
        },
    },
    watch: {
        async profile() {
            this.loadTargetProfile()
            currentProfile._loading.value = true
            this.messages = await currentProfile.chatter.getHistory(this.grouping.grouping_name)
            currentProfile.chatter.setOnMessage(this._onMessage)
            currentProfile._loading.value = false
        },
    },
    async created() {
        this.loadTargetProfile()
        currentProfile._loading.value = true
        this.grouping = this.getGrouping()
        this.them = this.grouping.profile
        this.messages = await currentProfile.chatter.getHistory(this.grouping.grouping_name)
        console.log('this.messages :>> ', this.messages)
        currentProfile.chatter.setOnMessage(this._onMessage)
        currentProfile._loading.value = false
    },
    methods: {
        async reveal(tagId) {
            const grouping = this.getGrouping()
            await grouping.reveal(currentProfile.id.value, tagId)
         },
        // TODO: remove, only for testing reveal()
        async checkData() {
            console.log('currentProfile :=>', currentProfile)
            // TODO: remove once Vue Router guards allow to redirect via url
            console.log('currentProfile.isComplete :=>', currentProfile.isComplete) // false
            console.log('currentProfile.isLoggedIn :=>', currentProfile.isLoggedIn) // true
        },
        /**
         * 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() {
            if (this.$route.params.pid === currentProfile.profile_id) {
                console.warn('WARNING :=> You cannot chat with yourself!!!')
            }
            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}`
                }
                this.target = grouping.profile
            } catch (err) {
                console.error(err)
            }
        },
    },
}
</script>

<style lang="sass">
main.view--chat
    article ul
        list-style: none
        > li
            font-family: sans-serif
            background-color: powderblue
            margin: 0 0.5em 1em 2em
            &.me
                margin: 0 2em 1em 0.5em
                background-color: lightgreen
            p:first-of-type
                font-size: 10px
</style>
