$(document).ready(function() {

    setTimeout(() => {
                    
        $("#content-meassages").scrollTop(15+80000);

    }, 3000);

    var recever_id = $('#reciver-id').val();
    var image_reciver = $('#image-reciver').val();
    var name_reciver = $('#name-reciver').val();
    var sender_id = $('#sender-id').val();
    var image_sender = $('#image-sender').val();

    $("#search-user").on("keyup", function() {

        var value = $(this).val().toLowerCase();
        $("#all-users a").filter(function() {
          $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
            
        });
        
    });    


    var db = firebase.firestore();

    function initIdToSide(sId, rId) {
        // when reciver writing
        db.collection("users").doc("userId_"+rId).onSnapshot(function(receverIds) {

            db.collection("users").doc("userId_"+sId).onSnapshot(function(senderIds) {

                console.log(receverIds.data().typingTo);
                console.log(senderIds.data().id);

                if (receverIds.data().typingTo === senderIds.data().id) {

                    $('#online').html('يكب الان ....');
                    
                } else {

                    $('#online').html('');

                }

            });

        }); // end of when reciver writing

        db.collection("users").doc('userId_'+sender_id).collection('chats').doc('receiver_id_'+recever_id).collection('messages')
        .get().then(function(querySnapshot) {
            if (querySnapshot.docs.length > 0) {
                for (var i in querySnapshot.docs) {
                    db.collection("users").doc('userId_'+sId).update({
                        'unReadingCount': null,
                    })
                    db.collection("users").doc('userId_'+sId).collection('chats').doc('receiver_id_'+rId).collection('messages').doc(querySnapshot.docs[i].id).update({
                        'read': true
                    })
                }
            }
        });
        
    }


    // get all messages
    db.collection("users").doc('userId_'+sender_id).collection('chats').doc('receiver_id_'+recever_id).collection('messages').orderBy('updated_at' , 'asc').onSnapshot(function(querySnapshot) {
           
        if(querySnapshot.docs.length != 0)
            {

                var str = '';
                var allConersionDate = {};
                for (var i in querySnapshot.docs) {

                    initIdToSide(sender_id, recever_id)

                    var class_dir = '';
                    var image = '';
                    if (querySnapshot.docs[i].data().receiver_id == recever_id) {
                        class_dir = '';
                        image = image_sender;
                    } else {

                        class_dir = 'reciever';

                        image = image_reciver;

                    }

                    if (querySnapshot.docs[i].data().updated_at != null) {
                        
                        const options = { year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric' };
                        var d = new Date(querySnapshot.docs[i].data().updated_at['seconds'] * 1000);

                        var message_date = d.toLocaleDateString('ar-EG', { year: 'numeric', month: 'long', day: 'numeric' });
                        var message_time = d.toLocaleTimeString('ar-EG', { hour: 'numeric', minute: 'numeric' });
                        
                        var isDateExist = message_date in allConersionDate;
                        if (!isDateExist) {
                            allConersionDate[message_date] = querySnapshot.docs[i].id;
                            str += '<p class="message-date" style="text-align:center">' + message_date + '</p>';
                        }


                        str += '<div class="chat-message first_color ' + class_dir + '">';
                        if (i == 0) {
                            str += '<div class="chat-img"><img src=' + window.location.origin + '/' + image + ' alt=""></div>';
                        } else if (querySnapshot.docs[(querySnapshot.docs.length - i) - 1].data().sender_id != sender_id) {
                            if ((i > 0 && querySnapshot != null && querySnapshot.docs[(querySnapshot.docs.length - i) - 1].data().sender_id != sender_id)) {
                                str += '<div class="chat-img"><img src=' + window.location.origin + '/' + image + ' alt=' + i + '></div>';
                            } else {
                                str += '';
                            }

                        } else if (querySnapshot.docs[(querySnapshot.docs.length - i) - 1].data().sender_id == sender_id) {
                            if ((i > 0 && querySnapshot != null && querySnapshot.docs[(querySnapshot.docs.length - i) - 1].data().sender_id == sender_id)) {
                                str += '<div class="chat-img"><img src=' + window.location.origin + '/' + image + ' alt=""></div>';
                            } else {
                                str += '';
                            }

                        }


                        if (querySnapshot.docs[i].data().type == 'text') {
                            str += '<div class="chat-bubble">' + querySnapshot.docs[i].data().message + '</div>';
                        } else if (querySnapshot.docs[i].data().type == 'file') {
                            str += '<img class="chat-bubble" width="150px" src=' + querySnapshot.docs[i].data().message + '>';
                        } else {
                            str += '<a class="chat-bubble" width="150px" href=' + querySnapshot.docs[i].data().message + '</a>';
                        }

                        str += '<div class="timechet"><span>' + message_time + '</span></div>';
                        str += '</div>';

                    }

                }
           
                $("#content-meassages").scrollTop(15+80000);
                
                $('#content-meassages').html(str);
            } else 
            {

                $('#content-meassages').html('<div class="enquiriesContainer" style="padding-top: 1.5rem; padding-bottom: 1.5rem;text-align: center;">' + 'لا يوجد محادثات' +
                '</div>');

            }
        }); /// get message bettwen sender and reciver



// when online show icon

var db = firebase.firestore();

// db.collection("users").doc("userId_"+recever_id).get().then(function(dat) {

    
//     if (dat.data().status == 'online') {

//         $('.main-chat-owner').addClass('online');

//     } else {

//         $('.main-chat-owner').removeClass('online');

//     }

// });        


}) // end of document


function searchPeerId(reciver, myArray) {
    for (var i = 0; i < myArray.length; i++) {
        var str = myArray[i].userId;
        var sendOrrecev = reciver.replace('receiver_id_' , '');
        if (str == sendOrrecev) {
            return  myArray[i];
        }
    }
}

// get all user with first messages
var allChatUsersList1 = [];
var allMessagesList = [];
var idRecever = '';
var allMessagesListReadCount = [];
var count = [];
var recever_id = $('#reciver-id').val();
var sender_id = $('#sender-id').val();


var db = firebase.firestore();
db.collection("users").doc('userId_'+sender_id).collection('chats').onSnapshot((value) => {

    value.docs.forEach((docUser) => {

        allChatUsersList1.push({

            'name': docUser.data().name,
            'photoUrl': docUser.data().photoUrl,
            'userId': docUser.data().userId,
            'status': docUser.data().status,
            'lastSeen': docUser.data().lastSeen,
            'typingTo': docUser.data().typingTo,
                
        });

        db.collection("users").doc('userId_'+sender_id).collection('chats').doc(docUser.id).collection('messages').orderBy('updated_at' , 'asc').onSnapshot(function(querySnapshot) {
            querySnapshot.docs.forEach(function(doc) {
    
                var peerId = docUser.id.replace('receiver_id_' , '');

                var peerData = searchPeerId(docUser.id , allChatUsersList1);

                if(peerData != undefined)
                {
                
                    const userMesIndex = allMessagesList.findIndex(user => user.userId === peerId);
        
                    if (userMesIndex === -1) {
        
                        var d = new Date(doc.data().updated_at * 1000);
        
                        var message_time = d.toLocaleTimeString('ar-EG', { hour: 'numeric', minute: 'numeric' });
                        var message_date = d.toLocaleDateString('ar-EG', { year: 'numeric', month: 'long', day: 'numeric' });
        
                        var image = 'صوره';
        
                        if (doc.data().unReadingCount) 
                        {
                            
                        }
        
                        if (doc.data().type != 'text') {
        
                            var message = '<p>' + image + ' </p>';
        
                        } else {
        
                            var message = '<p>' + doc.data().message + '</p>'
        
                        }
        
                        allMessagesList.push({
                            'countUnRead' : doc.data().unReadingCount,
                            'userId': peerId,
                            'name': peerData.name,
                            'userPhoto': peerData.photoUrl,
                            'content': message, // getContentValue(doc.data().content, doc.data().type),
                            'date': message_time, // getDateValue(doc.data().timestamp),
                            'allData': message_date, // getDateAllValue(doc.data().timestamp)
                        });
        
                        allMessagesListReadCount.push({
                            'userId': peerId,
                            'messageId': doc.id,
                            'status': doc.data().receiver_id == sender_id ? doc.data().read : true
                        });

                    } else {
        
                        const allMessagesListReadCountIndex = allMessagesListReadCount.findIndex(count => count.messageId === doc.id);
                        if (allMessagesListReadCountIndex === -1) {
                            allMessagesListReadCount.push({
                                'userId': peerId,
                                'messageId': doc.id,
                                'status': doc.data().receiver_id == sender_id ? doc.data().read : true
                            });
                            // console.log('allMessagesListReadCount');
                            // console.log(allMessagesListReadCount);
                            // console.log('allMessagesListReadCount');
                        } else {
                            const olduserId = allMessagesListReadCount[allMessagesListReadCountIndex].userId;
        
                            const olduserMessageId = allMessagesListReadCount[allMessagesListReadCountIndex].messageId;
                            allMessagesListReadCount[allMessagesListReadCountIndex] = {
                                'userId': olduserId,
                                'messageId': olduserMessageId,
                                'status': doc.data().receiver_id == sender_id ? doc.data().read : true
                            }
                        }
        
        
                        var d = new Date(doc.data().updated_at * 1000);
                      
                        var message_time = d.toLocaleTimeString('ar-EG', { hour: 'numeric', minute: 'numeric' });
                        var message_date = d.toLocaleDateString('ar-EG', { year: 'numeric', month: 'long', day: 'numeric' });
        
        
                        var image =  'تم ارسال مرفق';
        
                        if (doc.data().type != 'text') {
        
                            var message = '<p>' + image + ' </p>';
        
                        } else {
        
                            var message = '<p>' + doc.data().message + '</p>'
        
                        }
        
                        var newimage = peerData.photoUrl;
        
                        
                        allMessagesList[userMesIndex] = {
                            'countUnRead' : doc.data().unReadingCount,
                            'userId': peerId,
                            'name': peerData.name,
                            'userPhoto': newimage,
                            'slug': peerData.slug,
                            'content': message, //getContentValue(doc.data().content, doc.data().type),
                            'date': message_time, //getDateValue(doc.data().timestamp),
                            'allData': message_date //getDateAllValue(doc.data().timestamp)
                        };
                        //}
                    }

                }
    
            });

            if (allMessagesList.length == 0) {
                var str = '';
                str += '<div class="enquiriesContainer" style="padding-top: 1.5rem; padding-bottom: 1.5rem;text-align: center;">' + 'لا يوجد اعضاء' +
                    '</div>';
                $('#all-users').html(str);
            } else {
    
                var str = '';
                var str1 = '';
                //str+='<tr>';
    
                allMessagesList.forEach(function(message) {

                    var count = allMessagesListReadCount.filter(mess => mess.userId === message.userId && mess.status === false);

                    img_user = message.userPhoto;
                    
                    str += '<a class="link-url" href=" ' +
                        window.location.origin + '/dashboard/chat/' + message.userId +
                        '">' +
                        '<div class = "chat-img">' +
                        '<img src=' + img_user + ' alt="" />' +
                        '</div>' +
                        '<div class="side-contact-chat">' +
                        '<h3 class="second_color">' + message.name + '</h3>';
                    if (count.length > 0) {
                        str += '<span class="count-message">' + count.length + '</span>';
                    }
                    str += '<span class="message-time gray-color">' + message.date + '</span>'+
                        '<p>' +
                        message.content +
                        '</p>' +
                        '</div>' +
                        '</a>';
                });
    
    
                $('#all-users').html(str);
    
                // i++;
            }
        });
    });

    // var i = 0;



}); // end of get user


// scroll down
var scroll_bottom = function() {
    $(".chat-date").scrollTop(20000);
}
// end of scroll

// start form send message
var form = $('#form-chat');
var message = form.find('#input-chat');

form.submit(function(event) {

    event.preventDefault();

    // onFormSubmit(form);

    var receiver_id = $('#reciver-id').val();
    var image_reciver = $('#image-reciver').val();
    var name_reciver = $('#name-reciver').val();
    var image_sender = $('#image-sender').val();
    var name_sender = $('#name-sender').val();
    var sender_id = $('#sender-id').val();

    var db = firebase.firestore();
    
    db.collection("users").doc("userId_"+receiver_id).collection('chats').doc('receiver_id_'+sender_id).set({
        'name': name_sender,
        'photoUrl': window.location.origin + '/' + image_sender,
        'userId': sender_id,
        'status': 'offline',
        'lastSeen': firebase.firestore.FieldValue.serverTimestamp(),
        'typingTo': 0,
    });
    db.collection("users").doc("userId_"+sender_id).collection('chats').doc('receiver_id_'+receiver_id).set({
        'name': name_reciver,
        'photoUrl': window.location.origin + '/' + image_reciver,
        'userId': receiver_id,
        'status': 'online',
        'lastSeen': firebase.firestore.FieldValue.serverTimestamp(),
        'typingTo': 0,
    });
    
    // ======================================== START : create message ===============================
    // you
    db.collection("users").doc("userId_"+sender_id).collection('chats').doc('receiver_id_'+receiver_id).collection('messages').add({
        'updated_at': firebase.firestore.FieldValue.serverTimestamp(),
        'message': message.val(),
        'receiver_id': receiver_id,
        'sender_id': sender_id,
        'type': 'text',
        'read': false
    });
    // me
    db.collection("users").doc("userId_"+receiver_id).collection('chats').doc('receiver_id_'+sender_id).collection('messages').add({
        'updated_at': firebase.firestore.FieldValue.serverTimestamp(),
        'message': message.val(),
        'receiver_id': receiver_id,
        'sender_id': sender_id,
        'type': 'text',
        'read': false
    });
    // ======================================== END : create message ===============================

    $('#input-chat').val("");
    setTimeout(() => {
                
        $("#content-meassages").scrollTop(15+80000);

    }, 600);


}).on('keypress' , '#input-chat' ,  function (e) {

    console.log(message.val());
    
    if(e.which == 13 && message.val() != '') {

        var receiver_id = $('#reciver-id').val();
        var image_reciver = $('#image-reciver').val();
        var name_reciver = $('#name-reciver').val();
        var image_sender = $('#image-sender').val();
        var name_sender = $('#name-sender').val();
        var sender_id = $('#sender-id').val();
    
        var db = firebase.firestore();
        
        db.collection("users").doc("userId_"+receiver_id).collection('chats').doc('receiver_id_'+sender_id).set({
            'name': name_sender,
            'photoUrl': window.location.origin + '/' + image_sender,
            'userId': sender_id,
            'status': 'offline',
            'lastSeen': firebase.firestore.FieldValue.serverTimestamp(),
            'typingTo': 0,
        });
        db.collection("users").doc("userId_"+sender_id).collection('chats').doc('receiver_id_'+receiver_id).set({
            'name': name_reciver,
            'photoUrl': window.location.origin + '/' + image_reciver,
            'userId': receiver_id,
            'status': 'online',
            'lastSeen': firebase.firestore.FieldValue.serverTimestamp(),
            'typingTo': 0,
        });
        
        // ======================================== START : create message ===============================
        // you
        db.collection("users").doc("userId_"+sender_id).collection('chats').doc('receiver_id_'+receiver_id).collection('messages').add({
            'updated_at': firebase.firestore.FieldValue.serverTimestamp(),
            'message': message.val(),
            'receiver_id': receiver_id,
            'sender_id': sender_id,
            'type': 'text',
            'read': false
        });
        // me
        db.collection("users").doc("userId_"+receiver_id).collection('chats').doc('receiver_id_'+sender_id).collection('messages').add({
            'updated_at': firebase.firestore.FieldValue.serverTimestamp(),
            'message': message.val(),
            'receiver_id': receiver_id,
            'sender_id': sender_id,
            'type': 'text',
            'read': false
        });
        // ======================================== END : create message ===============================
    
        $('#input-chat').val("");
        setTimeout(() => {
                    
            $("#content-meassages").scrollTop(15+80000);
    
        }, 600);
        
    }
});
// end form send message

// send image chat
$("#form-chat").on("change", function() {

var recever_id = $('#reciver-id').val();
var sender_id = $('#sender-id').val();
var url = $(this).data('upload');

var image = $('#upload-chat')[0].files;

var formData = new FormData();

formData.append('image', image[0]);

$.ajax({
    headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
    url: url,
    type: "POST",
    cache: false,
    contentType: false, // you can also use multipart/form-data replace of false
    processData: false,
    data: formData,
    dataType: 'json',
    success: function(data) {

        $('#upload-chat').val('');
        $('#input-chat').val('');

        var read = false;
        // if (sender_id == recever_id) {
        //     read = true;
        // }

        // send message
        var db = firebase.firestore();

        var receiver_id = $('#reciver-id').val();
        var image_reciver = $('#image-reciver').val();
        var name_reciver = $('#name-reciver').val();
        var image_sender = $('#image-sender').val();
        var name_sender = $('#name-sender').val();
        var sender_id = $('#sender-id').val();
    
        var db = firebase.firestore();
        db.collection("users").doc("userId_"+receiver_id).collection('chats').doc('receiver_id_'+sender_id).set({
            'name': name_sender,
            'photoUrl': window.location.origin + '/' + image_sender,
            'userId': sender_id,
            'status': 'offline',
            'lastSeen': firebase.firestore.FieldValue.serverTimestamp(),
            'typingTo': 0,
        });
        db.collection("users").doc("userId_"+sender_id).collection('chats').doc('receiver_id_'+receiver_id).set({
            'name': name_reciver,
            'photoUrl': window.location.origin + '/' + image_reciver,
            'userId': receiver_id,
            'status': 'online',
            'lastSeen': firebase.firestore.FieldValue.serverTimestamp(),
            'typingTo': 1,
        });
        // ======================================== START : create message ===============================
        // you
        db.collection("users").doc("userId_"+sender_id).collection('chats').doc('receiver_id_'+receiver_id).collection('messages').add({
            'updated_at': firebase.firestore.FieldValue.serverTimestamp(),
            'message': window.location.origin + '/' + data.image,
            'receiver_id': receiver_id,
            'sender_id': sender_id,
            'type': 'file',
            'read': false
        });
        // me
        db.collection("users").doc("userId_"+receiver_id).collection('chats').doc('receiver_id_'+sender_id).collection('messages').add({
            'updated_at': firebase.firestore.FieldValue.serverTimestamp(),
            'message': window.location.origin + '/' + data.image,
            'receiver_id': receiver_id,
            'sender_id': sender_id,
            'type': 'file',
            'read': false
        })
        // ======================================== END : create message ===============================
        .then(function(docRef) {

            var docRef = db.collection("users").doc("userId_"+receiver_id);
            docRef.get().then(function(doc) {

                if (doc.exists) {
                    var unreadcount = doc.data().unReadingCount;
                    if (!read) {

                        // reciever
                        db.collection("users").doc("userId_"+receiver_id).update({
                            'unReadingCount': unreadcount + 1,
                            'typingTo': null
                        });

                    } else {

                        db.collection("users").doc("userId_"+receiver_id).update({
                            'typingTo': null
                        });

                    }
                } else {

                }
            }).catch(function(error) {

            });

            setTimeout(() => {
                
                $("#content-meassages").scrollTop(15+80000);

            }, 600);

        })
        .catch(function(error) {

        });

    }
});
});
// end of image chat


var db = firebase.firestore();
var recever_id = $('#reciver-id').val();
var sender_id = $('#sender-id').val();

// when auth writing
$("#input-chat").keyup(function() {

if ($('#input-chat').val().trim().length > 0) {
    
    db.collection("users").doc("userId_"+sender_id).update({
        'typingTo': "userId_" + recever_id
    });

    // when reciver writing
    db.collection("users").doc("userId_"+recever_id).onSnapshot(function(receverIds) {

        db.collection("users").doc("userId_"+sender_id).onSnapshot(function(senderIds) {

            console.log(receverIds.data().typingTo);
            console.log(senderIds.data().id);

            if (receverIds.data().typingTo === senderIds.data().id) {

                $('#online').html('يكب الان ....');

            }
            //  else {

            //     $('#online').html('نشط الأن');

            // }

        });

    }); // end of when reciver writing



} else {

    db.collection("users").doc("userId_"+sender_id).update({
        'typingTo': null
    });
}

}); // end of when auth writing

