var ref = new Firebase("https://ursugar-6ce9a.firebaseio.com/");
var messagesRef = ref.child("ChatMessages");
var AllMessages = new Array();
var AllPatients = new Array();
var KeyArray = new Array();
var KeyForDelete;
var INDoctorId = "";
var INPatientId = "";
var UserRef = ref.child("Users");
var Allusers = new Array();
var oldUser = new Array();
messagesRef.limitToFirst(1).on("child_added", function (snapshot) {
    var DoctorId = $('#myHiddenVar').val();
    var Configuration = {
        doctor_id: DoctorId,
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Message/GetPatientdetails',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Configuration),
        success: function (data) {
            AllPatients = data;
            GetPatientMessages();
        }
    });
});

function GetPatientMessages() {
    
    var DoctorId = $('#myHiddenVar').val();
    messagesRef.orderByChild('DoctorId').startAt(DoctorId).endAt(DoctorId).on("value", function (snapshot) {
        snapshot.forEach(function (child) {
            AllMessages.push(child.val())
            var newUserData = {
                "PatientId": child.val().PatientId,
                "DoctorId": child.val().DoctorId,
                "Key": child.key(),
                "Message": child.val().Message
            };
            KeyArray.push(newUserData);
        });
        $('#ChatContent').empty();
        var displayedPatientMessages = new Array();
        var ages = AllMessages.map(function (obj) { return obj.PatientId });
        ages = ages.filter(function (v, i) { return ages.indexOf(v) == i; });
        for (var i = 0; i < ages.length; i++) {
            var filtered = AllMessages.filter(function (x) { return x.PatientId == ages[i] && x.Message.indexOf(x.PatientId) > -1; });
            displayedPatientMessages.push(filtered[filtered.length - 1]);
        }
       
        for (var i = 0; i < displayedPatientMessages.length; i++) {
            var PatientName = AllPatients.filter(function (x) { return x.Patient_id == displayedPatientMessages[i].PatientId; });
            if (PatientName.length > 0 && PatientName[0].ChatStatus == 1) {

                loadOnlinePatientData(PatientName[0].Patient_first_Name, displayedPatientMessages[i])
            }
        }

        Allusers = [];
    });
}
UserRef.on("value", function (snapshot) {
    snapshot.forEach(function (child) {
        Allusers.push(child.val());
    });
        var ages = AllMessages.map(function (obj) { return obj.PatientId });
        ages = ages.filter(function (v, i) { return ages.indexOf(v) == i; });
        for (var i = 0; i < ages.length; i++) {
            var CurrentStatus = Allusers.filter(function (x) { return x.PatientId == ages[i] && x.Online.toString() == "true"; });
            var OldStatus = oldUser.filter(function (x) { return x.PatientId == ages[i] && x.Online.toString() == "true"; });
                if (CurrentStatus.length > 0 && OldStatus.length > 0) {
                }
                else {
                    GetPatientMessages();
                    break;
                }
        }
   
});
function loadOnlinePatientData(Patient_Name, displayedPatientMessages) {

    var Message = displayedPatientMessages.Message.replace(displayedPatientMessages.PatientId, '');
    var PatientId = displayedPatientMessages.PatientId;
    var DoctorRead = displayedPatientMessages.DoctorRead;
    var DoctorId = displayedPatientMessages.DoctorId;
    var PatientChatStatus = Allusers.filter(function (x) { return x.PatientId == PatientId && x.Online.toString() == "true"; });
    if (PatientChatStatus.length > 0) {
        var content = '<li class="contact"> <div class="wrap"><span class="contact-status online"></span><img src="../../Content/img/male.png" alt="" style="width: 50px;"/><div class="meta">';
        content = content + '<p class="name"><a onclick="return OpenChat(\'' + PatientId + '\')" href="#"><i class=" fa fa-circle text-danger"></i>' + Patient_Name + '</p><p class="preview">' + Message + '</p></div></div></li>';
        $('#ChatContent').append(content);
    }
}
function OpenChat(PatientId) {
   
    var MessageCount = 0;
    messagesRef.orderByChild('PatientId').startAt(PatientId).endAt(PatientId).on("value", function (snapshot) {
        snapshot.forEach(function (child) {
            if (MessageCount == 0)
            {
                $('#messageList').empty();
            }
            MessageCount = MessageCount + 1;
            addPatientMessage(child.val().DoctorId, child.val().PatientId, child.val().Message,child.key());
        });
        if (MessageCount > 0) {
            MessageCount = 0;
            $("#MessageInput")[0].style.display = "";
            $("#MessageInput")[0].style.display = "";
            $("#NoChat")[0].style.display = "none";
        }
        else {
            $("#MessageInput")[0].style.display = "none";
            $("#MessageInput")[0].style.display = "none";
            $("#NoChat")[0].style.display = "";
        }
        $('.nav-tabs a[href="#m"]').tab('show');
    });
   
}

function addPatientMessage(DoctorId, PatientId, Message, KeyForUpdate) {
    var el = "";
    INDoctorId = DoctorId;
    INPatientId = PatientId;
    ref.child('/ChatMessages/' + KeyForUpdate).update({ DoctorRead: 1 });
        if (Message.indexOf(DoctorId) > -1) {
            el = '<li class="replies"><img width="50" height="50" src="../../Content/img/user2-160x160.jpg" alt="" /><p>' + Message.replace(DoctorId, '') + '</p></li>';
        }
        else if (Message.indexOf(PatientId) > -1) {
            el = '<li class="sent"><img width="50" height="50" src="../../Content/img/male.png" alt="" /><p>' + Message.replace(PatientId, '') + '</p></li>';
        }
   
    $('#messageList').append(el);
}

function SubmitMessage() {
    if (document.getElementById("Doctormsg").value.length > 0) {
        sendMessage();
    } 
}

$("#Doctormsg").keypress(function (e) {
    if (e.keyCode == 13 && document.getElementById("Doctormsg").value.length > 0) {
        sendMessage();
    }
});
function sendMessage() {

    messagesRef.push({
        DoctorId: INDoctorId,
        PatientId: INPatientId,
        Message: INDoctorId + ' ' + document.getElementById("Doctormsg").value,
        TimeStamp: Date.now(),
        PatientRead: 0,
        DoctorRead: 1,
        IsStarred: 0
    }, function (error) {
        if (error) {
            console.log("Error adding new message:", error);
        }
    });
    document.getElementById("Doctormsg").value = "";
    $('#messageList').val("");
}

