"use strict";
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.0.0/firebase-app.js";
import { getMessaging, getToken, onMessage } from "https://cdnjs.cloudflare.com/ajax/libs/firebase/10.0.0/firebase-messaging.min.js";
var loaded_chat = [];
var msg_offset = '';
var msg_loaded = 0;
var chat_set_offset_id = false;
var target_height = '';
var new_msg_count = 0;
var new_msg_arrived = false;
var config = '';
var intervalChatHeart = '';
var window_is_focused = true;
var old_unread_msg = 0;
function requestPermission() {
    console.log('Requesting permission...');
    Notification.requestPermission().then((permission) => {
        if (permission === 'granted') {
            console.log('Notification permission granted.');
        }
    })
}

$(document).ready(function () {
    getOnlineMemebers();
});


window.onfocus = function () {
    window_is_focused = true;
    var oppo_user_id = $("#opposite_user_id").val();
    var type = $("#chat_type").val();
    if (loaded_chat[type + '_' + oppo_user_id] != undefined && !!loaded_chat[type + '_' + oppo_user_id]) {
        newLoadChat(oppo_user_id, type);
    }
};

function getOnlineMemebers() {

    $.ajax({
        url: base_url + "my-account/get_online_members",
        type: "GET",
        dataTpe: 'json',
        success: function (result) {
            var data = JSON.parse(result);

            if (data.length > 0) {

                $.each(data?.data?.members, function (key, val) {

                    var i = $("li").find("[data-id='" + val.id + "'][data-type='person'] i");
                    if (val.is_online == 1) {
                        i.removeClass("fa");
                        i.addClass("fa text-success");
                    } else {
                        i.removeClass("fa text-success");
                        i.addClass("fa");
                    }
                    i = $("li").find("[data-id='" + val.id + "'][data-type='person']");
                    old_unread_msg = (i.data("unread_msg") !== 0) ? i.data("unread_msg") : 0;

                    if (val.unread_msg > 0 && val.unread_msg > old_unread_msg) {
                        if (window_is_focused == false) {
                            newLoadChat(val.id, 'person');
                        }
                        i.find(".badge-chat").remove();
                        if (val.unread_msg > 9) {
                            i.append('<div class="badge-chat">9 +</div>');
                        } else {
                            i.append('<div class="badge-chat">' + val.unread_msg + '</div>');
                        }
                        i.data("unread_msg", val.unread_msg);
                    } else if (val.unread_msg == 0) {
                        i.find(".badge-chat").remove();
                    }

                });
            }

            setTimeout(getOnlineMemebers, 10000);

        }
    });
}

function makeMeOnline() {
    $.ajax({
        url: base_url + "my-account/make_me_online",
        type: "POST",
        data: csrfName + "=" + csrfHash,
        dataTpe: 'json',
        success: function (result) {

        }
    });
}


$(document).on('click', '#chat-preview-btn', function () {
    if ($("#chat-input-textarea-result").is(':visible')) {
        $('#chat-input-textarea-result').addClass("d-none");
    } else {
        $('#chat-input-textarea-result').removeClass("d-none");
    }
});


$(document).on('click', '#chat-scrn', function () {
    var data = $(this).data("value");
    if (data == 'max') {
        $('.main-footer').removeClass('chat-hide-show');
        $('.navbar-bg').removeClass('chat-hide-show');
        $('.navbar').removeClass('chat-hide-show');
        $('.main-sidebar').removeClass('chat-hide-show');
        $('.chat-full-screen').addClass('main-content').removeClass('chat-full-screen');
        $('.chat-max').addClass('chat-min').removeClass('chat-max');
        $('.fa-compress').addClass('fa-expand').removeClass('fa-compress');
        $(this).data("value", "min");
    } else {
        $('.main-footer').addClass('chat-hide-show');
        $('.navbar-bg').addClass('chat-hide-show');
        $('.navbar').addClass('chat-hide-show');
        $('.main-sidebar').addClass('chat-hide-show');
        $('.main-content').addClass('chat-full-screen').removeClass('main-content');
        $('.chat-min').addClass('chat-max').removeClass('chat-min');
        $('.fa-expand').addClass('fa-compress').removeClass('fa-expand');
        $(this).data("value", "max");
    }
});

$(document).on('click', '.floating-chat-back-btn', function () {
    console.log("here");
    $("#chat_area").addClass("d-none");
    $(".floating-chat-users").removeClass("d-none");

});

function getCaret(el) {
    if (el.selectionStart) {
        return el.selectionStart;
    } else if (document.selection) {
        el.focus();
        var r = document.selection.createRange();
        if (r == null) {
            return 0;
        }
        var re = el.createTextRange(),
            rc = re.duplicate();
        re.moveToBookmark(r.getBookmark());
        rc.setEndPoint('EndToStart', re);
        return rc.text.length;
    }
    return 0;
}

function getUserPicture(user_id) {
    $.ajax({
        url: base_url + "my-account/get_user_picture/" + user_id,
        type: "POST",
        data: csrfName + "=" + csrfHash,
        success: function (result) {
            var i = $("li").find("[data-id='" + user_id + "']");
            i.data("picture", result);
        }
    });
}

// sending msg
$(document).on('submit', '#chat-form2', function (e) {
    e.preventDefault();

    var to_id = $("#opposite_user_id").val();
    var type = $("#chat_type").val();
    var my_user_id = $("#my_user_id").val();
    var i = $("li").find("[data-id='" + my_user_id + "']");
    var me = $(this);
    var message = $("#chat-input-textarea").val();
    console.log(message);
    var convert = new Markdown.getSanitizingConverter().makeHtml;
    var string = convert(message);
    var chat_content = string.replace(/<[\/]{0,1}(p)[^><]*>/ig, "");
    var drop_file_count = myDropzone.files.length;

    if (message.length > 0) {
        var formData = new FormData(this);

        if (drop_file_count > 0) {

            myDropzone.on('sending', function (file, xhr, formData) {
                formData.append('opposite_user_id', jQuery('#opposite_user_id').val());
                formData.append('my_user_id', jQuery('#my_user_id').val());
                formData.append('chat_type', jQuery('#chat_type').val());
                formData.append('chat-input-textarea', jQuery('#chat-input-textarea').val());
            });

            myDropzone.processQueue();

            return false;

        }


        formData.append(csrfName, csrfHash);

        $.ajax({
            type: 'POST',
            url: base_url + "my-account/send_msg",
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            dataType: "json",
            success: function (result) {

                var new_msg = result.new_msg;

                // make sure loaded_chat var declared before adding a msg in var when first time msg received from fcm this var is not declared
                if (loaded_chat[type + '_' + to_id] != undefined) {
                    var chat_length = loaded_chat[type + '_' + to_id].length;
                    loaded_chat[type + '_' + to_id].unshift(Object.assign({}, new_msg[0]));
                }
                var user_name = new_msg[0].senders_name;

                var picture = '<figure class="avatar avatar-md"><img src="' + base_url + 'assets/front_end/classic/images/user.png" class="rounded-circle avtar_img"></figure>';

                $.chatCtrl('#mychatbox2', {
                    text: chat_content,
                    picture: picture,
                    user_name: user_name,
                    visiblity: 1,
                    media_files: '',
                    msg_id: (result.msg_id != undefined ? result.msg_id : ''),
                }, 'bottom');

                scrollToBottom();
                var from_id = $("#opposite_user_id").val();
                var type = $("#chat_type").val();
                $.ajax({
                    url: base_url + "my-account/load_chat",
                    type: "POST",
                    data: {
                        from_id: from_id,
                        type: type,
                    },
                    dataTpe: 'json',
                    success: function (result) {
                        var chats = JSON.parse(result);
                        var html = ''
                        var media_files = '';


                        $.each(chats['msg'], function (key, val) {

                            media_files = '';
                            if (!!val.media_files) {

                                $.each(val.media_files, function (key, val) {
                                    media_files += '<span class="chat-image-view d-grid"><a href="' + base_url + 'uploads/chat_media/' + val['original_file_name'] + '" download="' + val['original_file_name'] + '" class="download-btn-styling delete-msg fa fa-download"></a><img width="150px" src="' + base_url + 'assets/backend/chats/' + val['file_name'] + '"></span>';
                                });
                            }
                            html += '<div class="text-title ml-2 mb-2 text-muted">' + val.group_name + ' - ' + moment(val.date_created).utc().format('MMM Do, YYYY') + '</div><li class="media"><div class="chat-avtar-search">' + val.picture + '</div><div class="media-body"><div class="float-right text-primary">' + moment(val.date_created).utc().format('hh:mm A') + '</div><div class="media-title">' + val.senders_name + '</div><span class="text-small text-muted">' + val.message + ' ' + media_files + '</span></div></li>'
                        });


                        $("#show-search-result").removeClass("d-none");
                        $("#search-result").html(html);

                    }
                });

            }

        });
        $('#chat-input-textarea-result').addClass("d-none");
        $("#chat-input-textarea").val('');
        $("#chat-box-content").find('.chat-text').addClass('selectable');

    } else {
        if (drop_file_count > 0) {
            myDropzone.on('sending', function (file, xhr, formData) {
                formData.append('opposite_user_id', jQuery('#opposite_user_id').val());
                formData.append('my_user_id', jQuery('#my_user_id').val());
                formData.append('chat_type', jQuery('#chat_type').val());
                formData.append('chat-input-textarea', jQuery('#chat-input-textarea').val());
            });

            myDropzone.processQueue();
        }
    }
    return false;
});


$(document).on('click', '#delete_group', function (e) {
    e.preventDefault();
    var group_id = $(this).data("id");
    swal({
        title: 'Are you sure want to delete group ?',
        text: 'All messages and related media & attachments will be deleted forever, you will not be able to recover it later!',
        icon: 'warning',
        buttons: true,
        dangerMode: true,
    })
        .then((willDelete) => {

            if (willDelete) {
                deleteGroup(group_id);
            }
        });
});

function deleteGroup(group_id) {
    $.ajax({
        url: base_url + "my-account/delete_group/" + group_id,
        type: "POST",
        data: csrfName + "=" + csrfHash,
        success: function (result) {
            location.reload();
        }
    });
}

$(document).on('click', '.delete-msg-alert', function (e) {

    e.preventDefault();
    var msg_id = $(this).data("msg_id");
    Swal.fire({
        title: 'Are you sure?',
        text: 'Message Once deleted, you will not be able to recover that message!',
        icon: 'warning',
        buttons: true,
        dangerMode: true,
    })
        .then((willDelete) => {

            if (willDelete) {
                deleteMsg(msg_id);
            }
        });
});

function deleteMsg(msg_id) {
    $.ajax({
        url: base_url + "my-account/delete_msg/" + msg_id,
        type: "POST",
        data: csrfName + "=" + csrfHash,
        success: function (result) {
            var oppo_id = $("#opposite_user_id").val();
            var type = $("#chat_type").val();
            if (!!loaded_chat[type + '_' + oppo_id]) {

                for (var i = 0; i < loaded_chat[type + '_' + oppo_id].length; i++) {
                    if (loaded_chat[type + '_' + oppo_id][i].id == msg_id) {
                        loaded_chat[type + '_' + oppo_id].splice(i, 1);
                    }
                }

            }

            $("[data-delete_msg_id='" + msg_id + "']").slideUp("normal", function () {
                $(this).remove();
            });

            var receiver_id = $("#opposite_user_id").val();
            var title = 'msg deleted';
            var msg = msg_id;
            var type_1 = 'msg_delete';
            sendFCM(receiver_id, title, msg, type_1, type);
        }
    });
}


$(document).ready(function () {
    $(document).on('click', '#you_not_in_group_btn', function (e) {
        var group_id = $("#opposite_user_id").val();
        window.location = base_url + "my-account/super_admin_make_group_admin/" + group_id;
    });
});

// switching users
$(document).on('click', '.chat-person', function () {
    if ($(this).data("not_in_group") == true) {
        $("#chat_area_wait").addClass("d-none");
        $("#you_not_in_group").removeClass("d-none");
        $("#chat_area").addClass("d-none");
    } else {
        $("#chat_area_wait").addClass("d-none");
        $("#you_not_in_group").addClass("d-none");
        $("#chat_area").removeClass("d-none");
    }
    $(".floating-chat-users").addClass("d-none");
    $(".go-to-bottom-btn").hide();
    var oppo_user_id = $(this).data("id");
    var type = $(this).data("type");
    $('.chat-person').removeClass("active");
    $("#opposite_user_id").val(oppo_user_id);
    $("#chat_type").val(type);
    $(this).addClass("active");
    $("#chat-box-content").html('');
    switchChat(oppo_user_id, type);
    if (!!loaded_chat[type + '_' + oppo_user_id]) {

        var chat = loaded_chat[type + '_' + oppo_user_id]
        printChat(chat, oppo_user_id);

    } else {

        loadChat(oppo_user_id, type);
    }
    markMsgRead(oppo_user_id, type);

});

function markMsgRead(from_id, type) {
    $.ajax({
        url: base_url + "my-account/mark_msg_read",
        type: "POST",
        data: {
            from_id: from_id,
            type: type,
            [csrfName]: csrfHash
        },
        dataTpe: 'json',
        success: function (result) {

            var person = JSON.parse(result);
            csrfName = person.csrfName, csrfHash = person.csrfHash
            if (person.error == false) {
                var i = $("li").find("[data-id='" + from_id + "']");
                i.find(".badge-chat").remove();
                i.removeClass('new-msg-rcv');
                i.data("unread_msg", 0);
            } else {
                console.log('error');
            }
        }
    });

}

// this function run when tab is not active and user recieved a msg
function newLoadChat(from_id, type, offset = '', limit = '', sort = '', order = '') {
    offset = (!!offset) ? offset : 0;
    limit = (!!limit) ? limit : 10;
    $.ajax({
        url: base_url + "my-account/load_chat",
        type: "POST",
        data: {
            from_id: from_id,
            type: type,
            offset: offset,
            limit: limit,
            sort: sort,
            order: order,
            [csrfName]: csrfHash
        },
        dataTpe: 'json',
        success: function (result) {
            var chats = JSON.parse(result);
            csrfName = chats.csrfName, csrfHash = chats.csrfHash
            if (chats['error'] != true) {
                if (!!loaded_chat[type + '_' + from_id] && loaded_chat[type + '_' + from_id] != undefined) {

                    var new_msg_arved = 0;
                    for (var i = 0; i < chats['msg'].length; i++) {
                        if (loaded_chat[type + '_' + from_id][0].id < chats['msg'][i].id) {

                            new_msg_arved++;
                            new_msg_arrived = true;

                            loaded_chat[type + '_' + from_id].unshift(Object.assign({}, chats['msg'][i]));
                            loaded_chat[type + '_' + from_id]['msg_loaded'] = loaded_chat[type + '_' + from_id]['msg_loaded'] + new_msg_arved;
                            loaded_chat[type + '_' + from_id]['total_msg'] = loaded_chat[type + '_' + from_id]['total_msg'] + new_msg_arved;

                            var oppo_user_id = $("#opposite_user_id").val();
                            var type1 = $("#chat_type").val();

                            if (oppo_user_id == from_id && type1 == type) {
                                var convert = new Markdown.getSanitizingConverter().makeHtml;
                                var string = convert(chats['msg'][i].text);
                                var chat_content = string.replace(/<[\/]{0,1}(p)[^><]*>/ig, "");

                                var picture = '<figure class="avatar avatar-md"><img src="' + base_url + 'assets/front_end/classic/images/user.png" class="rounded-circle avtar_img"></figure>';

                                $.chatCtrl('#mychatbox2', {
                                    text: chat_content,
                                    picture: picture,
                                    user_name: chats['msg'][i].senders_name,
                                    position: 'chat-' + chats['msg'][i].position,
                                    visiblity: 1,
                                    media_files: (!!chats['msg'][i].media_files ? chats['msg'][i].media_files : ''),
                                    msg_id: chats['msg'][i].id
                                }, 'bottom');

                                $("#chat-box-content").find('.chat-text').addClass('selectable');
                            }

                        }
                    }

                }
            }
        }
    });
}

function loadChat(from_id, type, offset = '', limit = '', sort = '', order = '') {
    offset = (!!offset) ? offset : 0;
    limit = (!!limit) ? limit : 10;
    $.ajax({
        url: base_url + "my-account/load_chat",
        type: "POST",
        data: {
            from_id: from_id,
            type: type,
            offset: offset,
            limit: limit,
            sort: sort,
            order: order,
            [csrfName]: csrfHash
        },
        dataTpe: 'json',
        success: function (result) {
            var chats = JSON.parse(result);
            csrfName = chats.csrfName, csrfHash = chats.csrfHash
            if (chats['error'] != true) {
                if (!!loaded_chat[type + '_' + from_id] && loaded_chat[type + '_' + from_id] != undefined) {
                    loaded_chat[type + '_' + from_id] = loaded_chat[type + '_' + from_id].concat(chats['msg']);
                    loaded_chat[type + '_' + from_id]['msg_loaded'] = chats['msg'].length;
                    loaded_chat[type + '_' + from_id]['total_msg'] = chats['total_msg'];
                    loaded_chat[type + '_' + from_id]['offset'] = offset;
                    loaded_chat[type + '_' + from_id]['limit'] = limit;
                } else {
                    loaded_chat[type + '_' + from_id] = chats['msg'];
                    loaded_chat[type + '_' + from_id]['msg_loaded'] = chats['msg'].length;
                    loaded_chat[type + '_' + from_id]['total_msg'] = chats['total_msg'];
                    loaded_chat[type + '_' + from_id]['offset'] = offset;
                    loaded_chat[type + '_' + from_id]['limit'] = limit;
                }
                printChat(chats['msg'], from_id);
            }
        }
    });
}

function sendFCM(receiver_id, title, msg, type, message_type = '') {
    $.ajax({
        url: base_url + "my-account/send_fcm",
        type: "POST",
        data: {
            receiver_id: receiver_id,
            title: title,
            msg: msg,
            type: type,
            message_type: message_type
        },
        dataTpe: 'json',
        success: function (result) {
        }
    });
}

function printChat(chats, id_of_user) {
    if (0 < chats.length) {
        var last_msg = chats.length - 1;
        var picture = ''
        var old_date = '';
        for (var i = 0; i < chats.length; i++) {
            var type = 'text';
            var convert = new Markdown.getSanitizingConverter().makeHtml;
            var string = convert(chats[i].text);
            var chat_content = string.replace(/<[\/]{0,1}(p)[^><]*>/ig, "");
            var is_divide = 'no';
            var new_date = moment(chats[i].date_created).format('YYYYMMDD');

            if (i == 0) {
                old_date = moment(chats[i].date_created).format('YYYYMMDD');
                is_divide = 'yes';
            } else if (old_date != new_date) {
                is_divide = 'yes';
                old_date = new_date;
            } else if (i == last_msg) {
                is_divide = 'yes';
            }

            picture = '<figure class="avatar avatar-md"><img src="' + base_url + 'assets/front_end/classic/images/user.png" class="rounded-circle avtar_img"></figure>';

            if (chats[i].typing != undefined) type = 'typing';
            $.chatCtrl('#mychatbox2', {
                text: (chats[i].text != undefined ? chat_content : ''),
                picture: picture,
                user_name: chats[i].senders_name,
                position: 'chat-' + chats[i].position,
                time: moment(chats[i].date_created).format('hh:mm A'),
                chat_divider: is_divide,
                chat_divider_date: chats[i].date_created,
                visiblity: '',
                media_files: (!!chats[i].media_files ? chats[i].media_files : ''),
                msg_id: (chats[i].id != undefined ? chats[i].id : ''),
                type: type
            });

            $("#chat-box-content").find('.chat-text').addClass('selectable');
        }
        $(".chat_loader").remove();
        $("#chat-box-content").prepend('<div class="chat_loader">Loading...</div>');
    } else {
        $("#chat-box-content").html('');
        $(".go-to-bottom-btn").hide();
    }

    var type = $("#chat_type").val();
    if (!!loaded_chat[type + '_' + id_of_user]['msg_offset']) {

        $("#chat-box-content").scrollTop(loaded_chat[type + '_' + id_of_user]['msg_offset']);
    } else {
        if (target_height === '') {
            target_height = 640;
        }
        $("#mychatbox2").find('.chat-content').scrollTop(target_height, -1);
    }

}


function switchChat(from_id, type) {

    $.ajax({
        url: base_url + "my-account/switch_chat",
        type: "POST",
        data: {
            from_id: from_id,
            type: type,
            [csrfName]: csrfHash
        },
        dataTpe: 'json',
        success: function (result) {

            var person = JSON.parse(result);
            csrfName = person.csrfName,
                csrfHash = person.csrfHash

            if (type == 'person') {
                $("#chat_title").text(person[0].username);

                var html = '<figure class="avatar avatar-md"><img src="' + base_url + 'assets/front_end/classic/images/user.png" class="rounded-circle avtar_img"></figure>';

                $("#chat-avtar-main").html(html);

                if (person[0].is_online == 1) {
                    $("#chat_online_status").addClass("text-success");
                    $("#chat_online_status").html("<i class='fa fa-circle'></i> Online <span class='text-info' id='chat_typing' style='display: none;'> Typing...</span>");
                } else {
                    $("#chat_online_status").removeClass("text-success");
                    $("#chat_online_status").html("<i class='fa fa-circle'></i> Offline");
                }

            } else {


                $("#chat_title").html(person[0].title);
                var html = '<figure class="avatar avatar-md" data-initial="' + person[0].picture + '"></figure>';
                $("#chat-avtar-main").html(html);
                $("#chat_online_status").html('');
            }

        }
    });

}

function onSrollTopLoadChat() {
    if ($("#chat-box-content").scrollTop() == 0) {
        var oppo_user_id = $("#opposite_user_id").val();
        var type = $("#chat_type").val();
        if (loaded_chat[type + '_' + oppo_user_id] !== undefined) {
            var offset = loaded_chat[type + '_' + oppo_user_id]['offset'];
            var limit = loaded_chat[type + '_' + oppo_user_id]['limit'];
            offset = offset + limit;
            msg_loaded = msg_loaded + loaded_chat[type + '_' + oppo_user_id]['msg_loaded'];
            if (msg_loaded < loaded_chat[type + '_' + oppo_user_id]['total_msg']) {
                target_height = 640;
                $(".chat_loader").show();
                loadChat(oppo_user_id, type, offset, limit);
            } else {
                target_height = 0;
            }

        } else {
            target_height = 0;
        }
        $(".go-to-bottom-btn").show();

    }
}

function scrollToBottom() {
    var target_height_send = 0;
    var target_height_send_divider = 0;
    $('.chat-content .chat-item').each(function () {
        target_height_send += $(this).outerHeight();
    });
    $('.chat-content .chat_divider').each(function () {
        target_height_send_divider += $(this).outerHeight();
    });
    target_height_send = target_height_send + target_height_send_divider + 1000;
    $("#chat-box-content").scrollTop(target_height_send);
    $(".go-to-bottom-btn").hide();
}

function checkInView(elem, partial) {
    var container = $("#chat-box-content");
    var contHeight = container.height();
    var contTop = container.scrollTop();
    var contBottom = contTop + contHeight;

    var elemTop = $(elem).offset().top - container.offset().top;
    var elemBottom = elemTop + $(elem).height();

    var isTotal = (elemTop >= 0 && elemBottom <= contHeight);
    var isPart = ((elemTop < 0 && elemBottom > 0) || (elemTop > 0 && elemTop <= container.height())) && partial;

    return isTotal || isPart;
}
$(document).on("click", "#modal-edit-group-call", function () {

    var id = $(this).data("id");
    $.ajax({
        type: "POST",
        url: base_url + "my-account/get_group_members",
        data: {
            group_id: id
        },
        dataType: "json",
        success: function (result) {
            var title = result['data'][0].title;
            var description = result['data'][0].description;
            var update_id = result['data'][0].group_id;

            var user_ids = [];
            var admin_ids = [];
            $.each(result['data'], function (key, val) {
                user_ids[key] = val.user_id;
                if (val.is_admin == 1) {
                    admin_ids[key] = val.user_id;
                }
            });

            $('#update_id').val(update_id);
            $('#delete_group').attr("data-id", update_id);
            $('#update_title').val(title);
            $('#update_description').val(description);
            $('#update_users').val(user_ids);
            $('#update_users').trigger('change');

            $('#update_admins').val(admin_ids);
            $('#update_admins').trigger('change');

            $("#modal-edit-group").trigger("click");
        }
    });

});

$(document).on("click", "#modal-info-group-call", function () {

    var id = $(this).data("id");
    $.ajax({
        type: "POST",
        url: base_url + "my-account/get_group_members",
        data: {
            group_id: id
        },
        dataType: "json",
        success: function (result) {
            var title = result['data'][0].title;
            var description = result['data'][0].description;
            var update_id = result['data'][0].group_id;

            var user_ids = [];
            var admin_ids = [];

            $.each(result['data'], function (key, val) {
                user_ids[key] = val.user_id;
                if (val.is_admin == 1) {
                    admin_ids[key] = val.user_id;
                }
            });

            $('#update_id_info').val(update_id);
            $('#update_title_info').val(title);
            $('#update_description_info').val(description);
            $('#update_users_info').val(user_ids);
            $('#update_users_info').trigger('change');

            $('#update_admins_info').val(admin_ids);
            $('#update_admins_info').trigger('change');

            $("#modal-info-group").trigger("click");
        }
    });

});

Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("#myAlbum", {
    url: base_url + "my-account/send_msg",
    autoProcessQueue: false,
    paramName: "documents",
    addRemoveLinks: true,
    parallelUploads: 10,
    uploadMultiple: true,
    maxFiles: 3,
    dictMaxFilesExceeded: 'Only 3 file are allow at once',
    dictRemoveFile: 'x',

});


myDropzone.on("addedfile", function (file) {
    var i = 0;
    if (this.files.length) {
        var _i, _len;
        for (_i = 0, _len = this.files.length; _i < _len - 1; _i++) // -1 to exclude current file
        {
            if (this.files[_i].name === file.name && this.files[_i].size === file.size && this.files[_i].lastModifiedDate.toString() === file.lastModifiedDate.toString()) {
                this.removeFile(file);
            } else if (this.files[4] != null) {
                this.removeFile(file);

            }
            i++;
        }
    }
});

myDropzone.on('successmultiple', function (file, response) {
    var data = JSON.parse(response);
    console.log(data);
    var new_msg = data.new_msg;
    var to_id = $("#opposite_user_id").val();
    var message = $("#chat-input-textarea").val();

    var picture = '<figure class="avatar avatar-md"><img src="' + base_url + 'assets/front_end/classic/images/user.png" class="rounded-circle avtar_img"></figure>';


    $.chatCtrl('#mychatbox2', {
        text: new_msg[0].message,
        picture: picture,
        visiblity: '',
        media_files: (!!new_msg[0].media_files) ? new_msg[0].media_files : '',
        msg_id: (data.msg_id != undefined ? data.msg_id : ''),
    }, 'bottom');

    $('#chat-input-textarea-result').addClass("d-none");
    $("#chat-input-textarea").val('');
    $("#chat-box-content").find('.chat-text').addClass('selectable');

    // make sure loaded_chat var declared before adding a msg in var when first time msg received from fcm this var is not declared
    var type = $("#chat_type").val();
    if (loaded_chat[type + '_' + to_id] != undefined) {
        var chat_length = loaded_chat[type + '_' + to_id].length;
        loaded_chat[type + '_' + to_id].unshift(Object.assign({}, new_msg[0]));
    }
    closeDropZone();
    scrollToBottom();
});

$(document).on('change', '#chat_user', function () {

    console.log("here");

    var oppo_user_id = JSON.parse($("#chat_user").val())
    var type = 'person';
    if ($(this).data("not_in_group") == true) {
        $("#chat_area_wait").addClass("d-none");
        $("#you_not_in_group").removeClass("d-none");
        $("#chat_area").addClass("d-none");
    } else {
        $("#chat_area_wait").addClass("d-none");
        $("#you_not_in_group").addClass("d-none");
        $("#chat_area").removeClass("d-none");
    }
    $(".floating-chat-users").addClass("d-none");

    $(".go-to-bottom-btn").hide();

    $('.chat-person').removeClass("active");
    $("#opposite_user_id").val(oppo_user_id);
    $("#chat_type").val(type);
    $(this).addClass("active");
    $("#chat-box-content").html('');
    switchChat(oppo_user_id, type);
    if (!!loaded_chat[type + '_' + oppo_user_id]) {

        var chat = loaded_chat[type + '_' + oppo_user_id]
        printChat(chat, oppo_user_id);

    } else {

        loadChat(oppo_user_id, type);
    }
    markMsgRead(oppo_user_id, type);

});
$(document).ready(() => {
    /* check if user is trying to chat with some user directly  */
    var urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('user_id')) {
        var user_id = urlParams.get('user_id');
        console.log("user ID:", urlParams.get('user_id'));
        var type = 'person';
        if ($(this).data("not_in_group") == true) {
            $("#chat_area_wait").addClass("d-none");
            $("#you_not_in_group").removeClass("d-none");
            $("#chat_area").addClass("d-none");
        } else {
            $("#chat_area_wait").addClass("d-none");
            $("#you_not_in_group").addClass("d-none");
            $("#chat_area").removeClass("d-none");
        }
        $(".floating-chat-users").addClass("d-none");

        $(".go-to-bottom-btn").hide();

        $('.chat-person').removeClass("active");
        $("#opposite_user_id").val(user_id);
        $("#chat_type").val(type);
        $(this).addClass("active");
        $("#chat-box-content").html('');
        switchChat(user_id, type);
        if (!!loaded_chat[type + '_' + user_id]) {

            var chat = loaded_chat[type + '_' + user_id]
            printChat(chat, user_id);

        } else {

            loadChat(user_id, type);
        }
        markMsgRead(user_id, type);

    }
});
$('#chat_user').select2({
    ajax: {
        url: base_url + "/admin/Chat/get_members",
        data: function (params) {
            return { search: params.term };
        },
        processResults: function (data) {
            data = JSON.parse(data)
            return {
                results: data.data.map(function (item) {
                    return { id: item.id, text: item.username };
                })
            };
        }
    }
});
$('#chat_user_main').select2({
    ajax: {
        url: base_url + "/admin/Chat/get_members",
        data: function (params) {
            return { search: params.term };
        },
        processResults: function (data) {
            data = JSON.parse(data)
            return {
                results: data.data.map(function (item) {
                    return { id: item.id, text: item.username };
                })
            };
        }
    }
});

window.closeDropZone = function () {
    $('#chat-box-content').show();
    $('#chat-dropbox').addClass("d-none");
    Dropzone.forElement("#myAlbum").removeAllFiles(true);
}

window.showDropZone = function () {
    $('#chat-dropbox').removeClass("d-none");
    $('#chat-box-content').hide();
}
