let global_chat = {
    settings:{
        chat_url: null,
        countChat_url: null,
        chatList_url: null,
        chatPopup_url: null,
        chat_add_msgUrl: null,
    },
    userId: null,
    in_messenger_page: false,
    opened_chat_id: null,
    browserNotif: false,
    init: function(){
        global_chat.initIo();
        global_chat.initChat();
        global_chat.countChat(function(){});
        global_chat.checkBrowserPushNotif();
    },
    checkBrowserPushNotif: function(){


        // Let's check if the browser supports notifications
        if(global_chat.userId != null) {
            if (!("Notification" in window)) {
                alert("This browser does not support desktop notification");
            } // Let's check whether notification permissions have already been granted
            else if (Notification.permission === "granted") {
                // If it's okay let's create a notification
                global_chat.browserNotif = true;
            }// Otherwise, we need to ask the user for permission
            else {
                Notification.requestPermission().then(function (permission) {
                    // If the user accepts, let's create a notification
                    if (permission != "granted") {
                    } else {
                        global_chat.browserNotif = false;
                    }
                });
            }
        }
    },
    createNotification: function(){
      if(global_chat.browserNotif){
          if(/Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)){
              let options = {
                  body: 'New Message received',
                  icon: '/bundles/rxconnexion/admin/images/favicon.ico'
              };
              let n = new Notification('RxConnexion Chat', options);
          } else {
              let n = new Notification('RxConnexion Chat - New Message Received');
          }
      }
    },
    initIo: function(){
        if(global.io != null) {
            global.io.on('new msg sent', function(data) {
                global_chat.countChat(function(){
                    if(global_chat.in_messenger_page){
                        if(data.chatId == chat.chat_id && data.senderId != chat.userId){ // if the current open chat is equal to new message sent, and the sender of that message is not you, then append a new bubble
                            let cmc = '<div class="chat-msg-container">' +
                                '                <div class="chat-msg pull-right">' +
                                '                    <div> <a href="javascript:void(0)">' + data.senderName + '</a> <span class="chat-datetime">' + data.date + ' ' + data.time + '</span></div>' +
                                '                    <div>' + data.msg + '</div>' +
                                '                </div>' +
                                '                <div class="chat-avatar pull-left">' +
                                '                    <img src="/bundles/rxconnexion/admin/images/main-menu-default-avatar.png" />' +
                                '                </div>' +
                                '            </div>';
                            jQ('#txt-chat-msg').val('');
                            jQ('#chat-container').append(cmc);
                            jQ('#chat-conversation-container').scrollTop(jQ('#chat-conversation-container').scrollTop() + jQ('#txt-chat-msg').position().top);
                            global_chat.createNotification();
                        }
                        jQ("#chat-conversation-list li").each(function(i,el){
                            if(jQ(el).data('id') == data.chatId && data.senderId != chat.userId) {
                                jQ(el).children('.badge').removeClass('hide');
                            }
                        })
                    } else {
                        if(data.chatId == global_chat.chat_id){
                            if(data.senderId != global_chat.userId){
                                let cmc = '<div class="chat-msg-container">' +
                                    '                <div class="chat-msg pull-right">' +
                                    '                    <div> <a href="javascript:void(0)">' + data.senderName + '</a> <span class="chat-datetime">' + data.date + ' ' + data.time + '</span></div>' +
                                    '                    <div>' + data.msg + '</div>' +
                                    '                </div>' +
                                    '                <div class="chat-avatar pull-left">' +
                                    '                    <img src="/bundles/rxconnexion/admin/images/main-menu-default-avatar.png" />' +
                                    '                </div>' +
                                    '            </div>';
                                jQ('#chat-popup .txt-chat-msg').val('');
                                jQ('#chat-popup .chat-container').append(cmc);
                                jQ('#chat-popup').scrollTop(jQ('#chat-popup')[0].scrollHeight);

                                let ctr = jQ("#global-chat-ctr").html();
                                jQ("#global-chat-ctr").removeClass('hide').html(parseInt(ctr) + 1);
                                jQ(".global-chat-list").each(function(i,el){
                                    if(jQ(el).data('id') == data.chatId) {
                                        jQ(el).addClass('new');
                                    }
                                });

                                global_chat.createNotification();
                            }
                        } else {
                            if(data.senderId != global_chat.userId) {
                                global_chat.createNotification();
                            }
                        }
                    }
                });
            });
        }
    },
    initChat: function() {
        if(this.settings.chat_url != null) {
            jQ('#global-chat-toggle').unbind('click').bind('click', function() {
                let chatContent = jQ('#global-chat-content');
                if(chatContent.css('display') == 'block') {
                    chatContent.fadeOut(300);
                } else {
                    chatContent.slideDown(300);
                }
                return false;
            });
            jQ(document).unbind('click.fadeOutChat').bind('click.fadeOutChat', function(){
                jQ('#global-chat-content').fadeOut(300);
            });
            jQ('#global-chat-content').unbind('click').bind('click', function(){
                return false;
            });
            jQ('#global-chat-see-all').unbind('click').bind('click', function(){
                document.location = global_chat.settings.chat_url;
            });
            jQ('.global-chat-list').unbind('click').bind('click', function(){
                let chatContent = jQ('#global-chat-content');
                chatContent.fadeOut(300);
                global_chat.openPopupChat(jQ(this).data('id'));
                jQ(this).removeClass('new')
            });
            global_chat.countUnreadChatList();
        }
    },
    countUnreadChatList: function(){
        let ctr = 0;
        jQ(".global-chat-list.new").each(function(i,el){
            ctr++;
        });
        if(ctr > 0){
            jQ("#global-chat-ctr").removeClass('hide').html(ctr);
        } else {
            jQ("#global-chat-ctr").addClass('hide').html(ctr);
        }
    },
    countChat: function(callback) {
        global.ajaxCancel('countRecentChat');
        let settings = {
            url: global_chat.settings.countChat_url,
            type: 'GET',
            error: function(xhr, responseText) {
                if(responseText !== 'abort' && responseText !== 'error') {
                    alert(responseText);
                }
            },
            beforeSend: function(){
                // jQ('#global-recent-chat-ctr').html('<i class="fa fa-spin fa-spinner"></i>')
                jQ('#global-recent-chat-ctr').addClass('hide');
                jQ("#global-chat-list-container").addClass('has-loading');
                jQ("#global-chat-list-container").html('');
            },
            success: function(json) {
                if(json.success) {
                    if(json.ctr > 0) {
                        jQ('#global-recent-chat-ctr, #global-chat-ctr').removeClass('hide').html(json.ctr);
                    } else {
                        jQ('#global-recent-chat-ctr, #global-chat-ctr').addClass('hide').html(json.ctr);
                    }
                    jQ("#global-chat-list-container").removeClass('has-loading');
                    for(let i = 0; i < json.chats.length; i++){
                        let c = json.chats[i];
                        let html = '';
                        let seen = c.seen_latest == 0 ? 'new' : '';
                        if(c.chat_type == 'Private' && c.account_user_id != global_chat.userId) {
                            html = '<div class="global-chat-list ' + seen + '" data-id="' + c.chat_id + '"><i class="fa fa-user-circle"></i> ' + c.creatorFullName + '<!-- - <span>Good morning</span>--></div>';
                        } else {
                            html = '<div class="global-chat-list ' + seen + '" data-id="' + c.chat_id + '"><i class="fa fa-user-circle"></i> ' + c.description + '<!-- - <span>Good morning</span>--></div>';
                        }
                        jQ("#global-chat-list-container").append(html)
                    }
                    global_chat.initChat();
                    callback();
                } else {
                    // location.reload();
                }
            }
        };
        global.ajax(settings, 'countRecentChat');
    },
    openPopupChat: function(chat_id){
        global.ajaxCancel('chatPopup');
        let settings = {
            url: global_chat.settings.chatPopup_url,
            type: 'POST',
            data: { chat_id: chat_id },
            error: function(xhr, responseText) {
                if(responseText !== 'abort' && responseText !== 'error') {
                    alert(responseText);
                }
            },
            beforeSend: function(){
                jQ("#chat-popup").remove();
                jQ('body').append(`<div id="chat-popup"><div class="chat-header"><i class="fa fa-user-circle"></i><span style="text-transform: capitalize"><i class="fa fa-spinner fa-spin"></i></span></div><div class="chat-input-container"><input type="text" disabled placeholder="Enter your message here..." ></div></div>`);
            },
            success: function(json) {
                if(json.success) {
                    global_chat.chat_id = chat_id;
                    jQ('#chat-popup').html(json.html);
                    jQ('#chat-popup').scrollTop(jQ('#chat-popup')[0].scrollHeight);
                    jQ("#chat-popup .txt-chat-msg").focus();
                    global_chat.bindClosePopupChatEvent();
                    global_chat.bindTxtMsgBoxEvent();
                    global_chat.countUnreadChatList();
                } else {
                    // location.reload();
                }
            }
        };
        global.ajax(settings, 'chatPopup');
    },
    bindClosePopupChatEvent: function() {
        jQ('#chat-popup-close').unbind('click').bind('click', function() {
            global_chat.chat_id = null;
            jQ("#chat-popup").remove();
        });
    },
    bindTxtMsgBoxEvent: function() {
        jQ('#chat-popup .txt-chat-msg').unbind('keypress').bind('keypress', function(event){
            if(event.keyCode == 13){
                global_chat.addChatProcess();
            }
        });
    },
    addChatProcess: function(){
        let msg = jQ('#chat-popup .txt-chat-msg').val();

        if('' === msg) {
            return;
        }

        let refChatId = 'cdt-' + (Math.floor((Math.random() * 999) + 1)) + "-" + new Date().getTime(),
            cmc = '<div class="chat-msg-container">' +
                '                <div class="chat-msg pull-left">' +
                '                    <div class="chat-datetime" id="' + refChatId + '"><i class="fa fa-spinner fa-pulse"></i></div>' +
                '                    <div>' + msg + '</div>' +
                '                </div>' +
                '                <div class="chat-avatar pull-right">' +
                '                    <img src="/bundles/rxconnexion/admin/images/main-menu-default-avatar.png" />' +
                '                </div>' +
                '            </div>';

        jQ('#chat-popup .txt-chat-msg').val('');
        jQ('#chat-popup .chat-container').append(cmc);
        jQ('#chat-popup').scrollTop(jQ('#chat-popup')[0].scrollHeight);
        global_chat.chatSendProcess(refChatId, msg);
    },
    chatSendProcess: function(refId, msg) {
        let settings = {
            type: 'POST',
            url: global_chat.settings.chat_add_msgUrl,
            data: {
                chat_id: global_chat.chat_id,
                refId: refId,
                msg: msg
            },
            error: function() {
                //alert('Something went wrong, please try again. If the problem persist, please contact the administrator.');
                jQ('#' + refId).html('<i class="fa fa-refresh"></i>');
                jQ('#' + refId + ' i').bind('click', function() {
                    jQ('#' + refId).html('<i class="fa fa-spinner"></i>');
                    global_chat.chatSendProcess(refId, msg);
                });
            },
            success: function(json) {
                if(json.success) {
                    //eventTran_detail.chatList(false);
                    if(json.added) {
                        // eventTran_detail.chats.sent.push(json.id);
                        jQ('#' + refId).html(json.dt);
                        // TODO: Remove the refId from queue
                        //eventTran_detail.historyList();
                    } else {
                        jQ('#' + refId).html('<i class="fa fa-refresh"></i>');
                        jQ('#' + refId + ' i').bind('click', function() {
                            jQ('#' + refId).html('<i class="fa fa-spinner"></i>');
                            global_chat.chatSendProcess(refId, msg);
                        });
                    }
                } else {
                    // location.reload();
                }
            }
        };
        global.ajax(settings, 'chatAdd');
    },
}