﻿function g_addCurrentContact() {
    var requested = false;
    if (isSet(global_connection)) {
        if (global_connection.peerProfile != null) {
            if (global_connection.peerProfile.profileOwner != null) {
                if (confirm(g_tr.contact_add_usr)) {
                    global_connection.contactsManager.requestAddContact(global_connection.peerProfile.profileOwner);
                    alert(g_tr.contact_request_sent);
                    requested = true;
                } else {
                    return;
                }
            }
        }
    }

    if (!requested) {
        alert(g_tr.contact_must_chat);
    }
}

function g_removeContacts() {
    var ids = [];
    var prefix = "chk_ct_";
    j$('input[name*="chk_ct_"]').each(function (i, e) {
        if (e.checked) {
            ids.push(right(e.id, e.id.length - prefix.length));
        }
    });

    if (isSet(global_connection)) {
        if (ids.length > 0) {
            if (confirm(g_tr.contact_delete)) {
                global_connection.contactsManager.sendRemoveContacts(ids);
            }
        } else {
            alert(g_tr.contact_select_todelete);
        }
    }
}

function g_removeContact(userUUID) {
    if (isSet(global_connection)) {
        if (isSet(userUUID)) {
            global_connection.contactsManager.requestRemoveContact(userUUID);
        }
    }
}

function g_acceptContact() {
    var ids = [];
    var prefix = "chk_not_";
    j$('input[name*="chk_not_"]').each(function (i, e) {
        if (e.checked) {
            ids.push(right(e.id, e.id.length - prefix.length));
        }
    });

    if (isSet(global_connection)) {
        global_connection.contactsManager.sendAcceptContact(ids);
    }
}

function g_rejectContact() {
    var ids = [];
    var prefix = "chk_not_";
    j$('input[name*="chk_not_"]').each(function (i, e) {
        if (e.checked) {
            ids.push(right(e.id, e.id.length - prefix.length));
        }
    });

    if (isSet(global_connection)) {
        global_connection.contactsManager.sendRejectContact(ids);
    }
}



function ContactsManager(con) {
    this.connection = con;
    this.contactList = new Array(); // confirmed contacts
    this.yourRequestList = new Array(); // contacts request that you made
    this.notificationList = new Array(); // notified contacts request
    this.displayMode = "byname"; // "byname" = sorted by name; "byonline" = sorted by online/offline then by name

    // add listeners
    con.messageListeners.addListener(new MessageListener("msg2", "notify", "contactNotify", global_DefaultSchema, internalHandleContactNotify, this));
    con.messageListeners.addListener(new MessageListener("msg2", "notify", "contactList", global_DefaultSchema, internalHandleContactListNotify, this));
    con.messageListeners.addListener(new MessageListener("msg2", "response", "contactList", global_DefaultSchema, internalHandleContactListNotify, this));
    con.messageListeners.addListener(new MessageListener("msg2", "response", "contactAction", global_DefaultSchema, internalHandleContactListNotify, this));
}

ContactsManager.prototype = {
    contactComparerByNickname: contactsManager_ContactComparerByNickname,
    getOnlineContacts: contactsManager_GetOnlineContacts,
    getOfflineContacts: contactsManager_GetOfflineContacts,
    getIndexByNickname: contactsManager_GetIndexByNickname,
    getContactsByNickname: contactsManager_GetContactsByNickname,
    getIndexByUUID: contactsManager_GetIndexByUUID,
    removeContactPrimitive: contactsManager_RemoveContact_Primitive,
    updateContactPrimitive: contactsManager_UpdateContact_Primitive,
    updateManyContactsPrimitive: contactsManager_UpdateManyContacts_Primitive,
    displayContactsByNicknames: contactsManager_DisplayContactsByNicknames,
    cloneArray: contactsManager_CloneArray,
    loadContacts: contactsManager_LoadContacts,
    requestRemoveContact: contactsManager_RequestRemoveContact,
    sendRemoveContacts: contactsManager_SendRemoveContacts,
    requestAddContact: contactsManager_RequestAddContact,
    sendAcceptContact: contactsManager_SendAcceptContact,
    sendRejectContact: contactsManager_SendRejectContact,
    close: contactsManager_Close
}

function contactsManager_ContactComparerByNickname(c1, c2) {
    var lowC1 = c1.nickname.toLowerCase();
    var lowC2 = c2.nickname.toLowerCase();

    if (lowC1 < lowC2) {
        return -1;
    }

    if (lowC2 < lowC1) {
        return 1;
    }

    return 0;
}

function contactsManager_GetOnlineContacts() {
    var onlineContacts = new Array();
    for (var i = 0; i < this.contactList.length; i++) {
        if (this.contactList[i].IsOnline) {
            onlineContacts.push(this.contactList[i]);
        }
    }
    return onlineContacts;
}

function contactsManager_GetOfflineContacts() {
    var offlineContacts = new Array();
    for (var i = 0; i < this.contactList.length; i++) {
        if (!this.contactList[i].IsOnline) {
            offlineContacts.push(this.contactList[i]);
        }
    }
    return offlineContacts;
}

function contactsManager_GetIndexByNickname(contactArray, nickname) {
    var n0 = nickname.toLowerCase();
    for (var i = 0; i < this.contactList.length; i++) {
        var n = this.contactList[i].nickname.toLowerCase();
        if (n == n0) {
            return i;
        }
    }

    return -1;
}

function contactsManager_GetContactsByNickname(nickname) {
    var n0 = nickname.toLowerCase();
    var contacts = new Array();
    var _lists = [this.contactList, this.yourRequestList];

    for (var k = 0; k < _lists.length; k++) {
        var L = _lists[k];
        for (var i = 0; i < L.length; i++) {
            var n = L[i].nickname.toLowerCase();
            if (n == n0) {
                contacts.push(L[i]);
            }
        }
    }

    return contacts;
}

function contactsManager_GetIndexByUUID(contactArray, uuid) {
    for (var i = 0; i < contactArray.length; i++) {
        var _uuid = contactArray[i].uniqueid;
        if (_uuid == uuid) {
            return i;
        }
    }

    return -1;
}


function contactsManager_RemoveContact_Primitive(contactArray, uniqueid) {
    var index = this.getIndexByUUID(contactArray, uniqueid);
    if (index > -1) {
        contactArray.splice(index, 1);
    }
}

function contactsManager_UpdateContact_Primitive(contactArray, contact) {
    var uniqueid = contact.uniqueid;
    var index = this.getIndexByUUID(contactArray, uniqueid);
    if (index > -1) {
        contactArray[index] = contact;
    } else {
        contactArray.push(contact);
    }
}

function contactsManager_UpdateManyContacts_Primitive(contactArray, newContactsArray) {
    for (var i = 0; i < contactArray.length; i++) {
        this.updateContactPrimitive(contactArray, newContactsArray[i]);
    }
}


function contactsManager_DisplayContactsByNicknames(contactArray, yourRequestArray, notifyArray) {
    var arrays = [contactArray, yourRequestArray, notifyArray];
    var divids = ["contacts_acceptedlist", "contacts_yourRequestList", "contacts_notifylist"];
    var panelsids = ["", "contacts_yourRequestList_panel", "contacts_notifylist_panel"];
    var headersids = ["", "contacts_yourRequestList_header", "contacts_notifylist_header"];
    var prefixes = ["chk_ct_", "chk_req_", "chk_not_"];

    for (var k = 0; k < arrays.length; k++) {
        var duplicateArray = this.cloneArray(arrays[k]);
        duplicateArray.sort(this.contactComparerByNickname);
        var divObj = j$("#" + divids[k]);
        divObj.html("");
        var colCount = 1;
        var rowCount = Math.ceil(duplicateArray.length / colCount);

        // hide notification and your-requests panels in case they are empty
        if (k > 0) {
            if (rowCount == 0) {
                j$("#" + headersids[k]).hide();
                j$("#" + panelsids[k]).hide();
            } else {
                j$("#" + headersids[k]).show();
                j$("#" + panelsids[k]).show();
            }
        }

        var htmlStr = "<table>";
        for (var i = 0; i < rowCount; i++) {
            htmlStr += "<tr>";
            for (var j = 0; j < colCount; j++) {
                var index = (i * colCount) + j;
                if (index < duplicateArray.length) {
                    var ct = duplicateArray[index];

                    htmlStr += "<td><input type='checkbox' name='" + prefixes[k] + ct.uniqueid + "' id='" + prefixes[k] + ct.uniqueid + "'/></td>";

                    htmlStr += "<td>";
                    htmlStr += "<a><img src='" + ct.imgurl + "'>";
                    htmlStr += "</a>";
                    htmlStr += "</td>";

                    htmlStr += "<td><span class='contact_nickname'>";
                    var str = "";
                    if (ct.nickname != "") {
                        str += ct.nickname;
                    }
                    htmlStr += str + "</span><span class='contact_text'>";
                    str = "";
                    if (ct.distance != "" && ct.distance != null) {
                        str = ((ct.nickname != null && ct.nickname.length > 0) ? ", " : "") + ct.distance + " away";
                    }
                    htmlStr += str + "</span></td>";
                } else {
                    htmlStr += "<td></td><td></td>";
                    break;
                }
            }
            htmlStr += "</tr>";
        }
        htmlStr += "</table>";
        divObj.html(htmlStr);
    }

}

function contactsManager_CloneArray(array) {
    var newArray = new Array();
    for (var i = 0; i < array.length; i++) {
        newArray.push(array[i]);
    }
    return newArray;
}

// handles Contact notification from the server
function internalHandleContactNotify(sender, message, targetObject) {
    if (!isSet(message.action)) {
        return;
    }

    if (message.action == "requestAdd") {
        alert("request add from " + message.fromNickname);
    }
}

function internalHandleContactListNotify(sender, message, targetObject) {
    if (isSet(message.success) && (message.success == "false" || message.success == false)) {
        alert(message.errcode + " - " + message.errmsg);
        return;
    }

    if (isSet(targetObject) && isSet(message.contacts) && isSet(message.action)
        && (message.action == "update" || message.action == "init")) {
        var contacts = message.contacts;
        for (var i = 0; i < contacts.length; i++) {
            var ct = contacts[i];
            var index = -1;

            // if pending add it to yourRequestList
            if (ct.type == "Contact") {
                index = targetObject.getIndexByUUID(targetObject.yourRequestList, ct.uniqueid);
                if (ct.requestStatus == "Pending") {
                    if (index == -1) {
                        targetObject.yourRequestList.push(ct);
                    } else {
                        targetObject.yourRequestList[index] = ct;
                    }
                } else if (ct.requestStatus == "Accepted") {
                    // if accepted remove it from the yourRequestList and add it to contactList
                    if (index > -1) {
                        targetObject.yourRequestList.splice(index, 1);
                    }

                    // update contactlist
                    targetObject.updateContactPrimitive(targetObject.contactList, ct);
                } else if (ct.requestStatus == "Removed") {
                    // if Removed then remove it from the yourRequestList and from contactList
                    if (index > -1) {
                        targetObject.yourRequestList.splice(index, 1);
                    } else {
                        index = targetObject.getIndexByUUID(targetObject.contactList, ct.uniqueid);
                        if (index > -1) {
                            targetObject.contactList.splice(index, 1);
                        }
                    }
                }
            } else if (ct.type == "ContactRequest") { // check if this is an incoming request
                index = targetObject.getIndexByUUID(targetObject.notificationList, ct.uniqueid);
                if (ct.requestStatus == "Pending") {
                    if (index == -1) {
                        targetObject.notificationList.push(ct);
                    } else {
                        targetObject.notificationList[index] = ct;
                    }
                } else if (ct.requestStatus == "Accepted") {
                    // if accepted remove it from the notificationList and add it to contactList
                    if (index > -1) {
                        targetObject.notificationList.splice(index, 1);
                    }

                    // update contactlist
                    targetObject.updateContactPrimitive(targetObject.contactList, ct);
                } else if (ct.requestStatus == "Removed") {
                    // if Removed then remove it from the notificationList and from contactList
                    if (index > -1) {
                        targetObject.notificationList.splice(index, 1);
                    } else {
                        index = targetObject.getIndexByUUID(targetObject.contactList, ct.uniqueid);
                        if (index > -1) {
                            targetObject.contactList.splice(index, 1);
                        }
                    }
                }
            }
        }

        // update the UI
        if (contacts.length > 0) {
            targetObject.displayContactsByNicknames(targetObject.contactList, targetObject.yourRequestList, targetObject.notificationList);
        }
    }
}

function contactsManager_Close() {
    var divObj = j$("#contacts_acceptedlist");
    divObj.html("");

    divObj = j$("#contacts_yourRequestList");
    divObj.html("");

    divObj = j$("#contacts_notifylist");
    divObj.html("");

    this.contactList = new Array();
    this.yourRequestList = new Array();
    this.notificationList = new Array();
}

function contactsManager_LoadContacts() {
    var msg = createLoadContactsMessage(this.connection.nextMessageID);
    this.connection.postMessageObject(msg);
}

function contactsManager_RequestRemoveContact(userUUID) {
    var msg = createContactActionMessage(this.connection.nextMessageID(), "remove", [userUUID]);
    this.connection.postMessageObject(msg);
}

function contactsManager_RequestAddContact(userUUID) {
    var msg = createContactActionMessage(this.connection.nextMessageID(), "add", [userUUID]);
    this.connection.postMessageObject(msg);
}

function contactsManager_SendAcceptContact(idsArray) {
    if (idsArray.length > 0) {
        var msg = createContactActionMessage(this.connection.nextMessageID(), "accept", idsArray);
        this.connection.postMessageObject(msg);
    }

}

function contactsManager_SendRejectContact(idsArray) {
    if (idsArray.length > 0) {
        var msg = createContactActionMessage(this.connection.nextMessageID(), "reject", idsArray);
        this.connection.postMessageObject(msg);
    }
}


function contactsManager_SendRemoveContacts(idsArray) {
    if (idsArray.length > 0) {
        var msg = createContactActionMessage(this.connection.nextMessageID(), "remove", idsArray);
        this.connection.postMessageObject(msg);
    }

}
