
function initAgentGrid(queue_id)
{
    ws.command({
        name:"requestQueueAgents",
        type:"command",
        data:{queue_id:queue_id},
        uuid: ws.generateUUID()
    });
}

function updateAgentGrid(agent)
{
    if (isDisplayedAgent(agent)) {
        updateDisplayedAgent(agent);
    } else {
        addAgentToGrid(agent);
    }
}

function isDisplayedAgent(agent) 
{
    if ($("#agent-grid tbody tr[data-userid='"+agent.userId+"']").length > 0) {
        return true;
    }
    return false;
}

function addAgentToGrid(agent)
{
    var prototypeRow = $("#agent-grid tbody tr:first-child").clone();
    prototypeRow.find(".logginButton").remove();
    prototypeRow.removeClass("hideRow");
    prototypeRow.attr("data-userid",agent.userId);
    prototypeRow.find(".state").text("");
    createNewLogginButton(prototypeRow, agent);
    $.each(agent, function (key, value) {
        if (key !== "loggedIn" && key !== "agent_name" && key !== "name") {
            prototypeRow.find("."+key).text(value);
        }
    });
    setAgentName(prototypeRow, agent);
    setDefaultCallStatus(prototypeRow, agent);
    $("#agent-grid tbody").append(prototypeRow);
}

function updateDisplayedAgent(agent)
{
    var row = $("#agent-grid tbody tr[data-userid='" + agent.userId + "']");

    if (row.length === 0) {
        addAgentToGrid(agent);
    } else {
        updateLogginButton(row, agent);
        $.each(agent, function (key, value) {
            if (key !== "loggedIn" && key !== "name" && key !== "agent_firstname") {
                row.find("." + key).text(value);
            }
        });
        setAgentName(row, agent);
    }
}

function removeDisplayedAgentFromQueue(agent)
{
    var row = $("#agent-grid").find("tr[data-userid='"+agent.userId+"']");
    if (row.find(".logginButton").length === 1) {
        row.remove();
    } else {
        var loginButton = row.find(".logginButton[data-agentid='"+agent.id+"']");
        loginButton.remove();
    }
}

function createNewLogginButton(row, agent)
{
    var logginButtonPrototype = $("#agent-grid tbody tr:first-child .logginButton").clone();
    logginButtonPrototype.attr("data-agentid", agent.id);
    logginButtonPrototype.text(agent.name);
    setLogginButtonText(logginButtonPrototype, agent);
    setStateSensitiveLoginButtonAttributes(logginButtonPrototype, agent);
    logginButtonPrototype.tooltip();
    if (toggleAgentLoginIds.indexOf(agent.id) === -1) {
        logginButtonPrototype.addClass("disabled");
    }
    row.find(".loggedIn").append(logginButtonPrototype);
}

function updateLogginButton(row, agent)
{
    var logginButton = row.find(".logginButton[data-agentid='"+agent.id+"']");
    if (logginButton.length === 0) {
        createNewLogginButton(row, agent);
    } else {
        logginButton.attr("data-queueid", agent.queueId);
        logginButton.attr("data-agentid", agent.id);
        setLogginButtonText(logginButton, agent);
        setStateSensitiveLoginButtonAttributes(logginButton, agent);
    }
    
}

function setStateSensitiveLoginButtonAttributes(button, agent)
{
    if (agent.static_member === true) {
        button.removeClass("btn-success").removeClass("btn-danger");
        button.attr("data-original-title", translatedStaticMemberText);
    } else {
        if (agent.loggedIn === false) {
            button.removeClass("btn-success").addClass("btn-danger");
            button.attr("data-original-title", translatedLoginText);
        } else {
            button.addClass("btn-success").removeClass("btn-danger");
            button.attr("data-original-title", translatedLogoutText);
        }
    }
}

$("#agent-grid").on("click", ".logginButton", function()
{
    if (toggleAgentLoginIds.indexOf($(this).data("agentid")) !== -1) {
        if ($(this).hasClass("btn-success")) {
            ws.command({
                name:"logoutQueue",
                type:"command",
                data: {
                    id:$(this).data("agentid")
                },
                uuid: ws.generateUUID()
            });
        } else if ($(this).hasClass("btn-danger")) {
            ws.command({
                name:"loginQueue",
                type:"command",
                data: {
                    id:$(this).data("agentid")
                },
                uuid: ws.generateUUID()
            });
        }
    }
});

function setAgentName(row, agent)
{
    var formattedAgentName = "<"+agent.agent_extension+"> "+agent.agent_firstname+" "+agent.agent_lastname;
    row.find(".agent_firstname").text(formattedAgentName);
    
}

function setLogginButtonText(button, agent)
{
   var formattedQueueName = "<"+agent.extension+"> "+ agent.name;
   button.text(formattedQueueName);
}

function setDefaultCallStatus(row,agent)
{
    var icon = $("<i />");
    icon.addClass("icon-phone");
    icon.css("font-size","25px");
    icon.css("color",getPhonePresenceColor(agent));
    
    var iconContainer = $("<div />");
    iconContainer.addClass("droppable");
    iconContainer.addClass("fade");
    iconContainer.addClass("in");
    iconContainer.append(icon);
    iconContainer.attr("data-target", agent.agent_extension);
    iconContainer.attr("data-agentid", agent.id);

    row.find(".state").append(iconContainer);
    initDroppable(row);
}

function updateAgentPhonePresence(agent)
{
    var row = $("#agent-grid tr[data-userid='"+agent.id+"']");
    if (row.length > 0) {
        var icon = row.find(".state .icon-phone");
        icon.css("color", getPhonePresenceColor(agent));
    }
}

function getPhonePresenceColor(agent)
{
    var stateColor = "";
    switch (agent.phonePresence) {
        case 'offline':
            stateColor = 'gray';
            break;
        case 'ringing':
            stateColor = "#ff9200";//'yellow';
            break;
        case 'free':
            stateColor = 'green';
            break;
        case 'busy':
            stateColor = 'red';
            break;
        case 'hold':
            stateColor = 'orange';
            break;
        case 'online':
            stateColor = 'green';
            break;
        default:
            stateColor = 'gray';
    }
    return stateColor;
}

function initDroppable(row) 
{
    if (transferCallToPermissions.indexOf($(row).find(".droppable").data("agentid")) !== -1) {
        row.find(".droppable").droppable({
            drop: function( event, ui ) {
                $(ui.draggable.context).draggable( "disable" );

                ws.command({
                    name:"queueCallTransfer",
                    type:"command",
                    data:{
                        target_tier_id: $(this).data("agentid"),
                        target:$(this).data("target"),
                        callid:$(ui.draggable.context).find("i").data("callid")
                    },
                    uuid: ws.generateUUID()
                });
            }
        });
    }
}
