<template>
    <div class="nav-item dropdown no-arrow">
        <a class="dropdown-toggle nav-link" aria-expanded="false" data-toggle="dropdown" href="#">
            <span class="badge badge-danger badge-counter">{{countNotificationsUnread}}</span>
            <i class="fas fa-bell fa-fw" style="color: #ffffff;"></i>
        </a>
        <div class="dropdown-menu dropdown-menu-right dropdown-list animated--grow-in">
            <h6 class="dropdown-header" style="background: #5d6270;">Notifications (placeholder)</h6><a class="dropdown-item d-flex align-items-center" href="#">
                <div class="mr-3">
                    <div class="bg-primary icon-circle"><i class="fas fa-file-alt text-white"></i></div>
                </div>
                <div><span class="small text-gray-500">May 4, 2021</span>
                    <p v-for="(message, indexNotifications) of notificationList" :key="indexNotifications">{{message.title}}</p>
                </div>
            </a><a class="dropdown-item text-center small text-gray-500" href="#">Show All Alerts</a>
        </div>
    </div>
</template>
<script lang="ts">
import { MessageNotification } from "@/domain/models/notifications/MessageNotification.interface";
export default {
    name: 'Notifications',
    data: () => {
        return {
            eventSource: EventSource,
            countNotifications: 0,
            notifications: [],
        }
    },
    async mounted(){
        this.connectToSSE();
    },
    methods:{
        connectToSSE(){
            this.eventSource = new EventSource(process.env.VUE_APP_ROOT_API + '/sse/alert/');
            this.eventSource.onmessage = ( ev: any) => {
                console.log('onmessage');
                this.countNotifications++;
                let data: MessageNotification;
                data = JSON.parse(ev.data);
                data.id = this.countNotifications;
                let date = new Date();
                data.viewed = false;
                data.title = data.title +  " " + date.toString();
                this.notifications.push(data);
                this.countNotifications++;
                console.log('MessageNotification',data, this.countNotifications);
            }
        }
    },
    computed:{
        notificationList(){
            return this.notifications.sort((itemA: MessageNotification, itemB: MessageNotification) => { return ( itemB.id - itemA.id )});
        },
        countNotificationsUnread(){
            console.log('Noti ===>', this.notifications);
            console.log('Total ===>', this.notifications.filter((item: MessageNotification) => { item.viewed == false}));
            return this.notifications.filter((item: MessageNotification) => { item.viewed == false}).length;
        }
        
    }
}
</script>