////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Controller  - Sample Client //////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var _iframeId = 'iframeDiv';
var _acinstance = null;
var _success_message;
var _fail_message;

function AgentControllerInit() {

    console.info('Load Complete ' + '[jQuery]: ' + $().jquery);
    console.info('Successfully Initilized');
    
}

function getVersion() {
    this.createInstance();
    return _acinstance.getVersion();
}

function authorizationSettings() {
    if ($("#enableAuthorization").is(':checked')) {
        $("#Authorization").show();
    } else {
        $("#Authorization").hide();
    }
}

function createInstance() {
    var clusterIP = $('#clusterIP').val();
    var enableDev = ($("#enableDev").is(':checked') ? false : true);
    var guestUsage = ($("#enableAuthorization").is(':checked') ? false : true);
    resetResponse();

    _acconfig = new AvayaCustomerInteractionUtilitiesClient.Config.AcConfiguration();
    console.info('agent controller Engine Load Complete');
    console.info('[jQuery]: ' + $().jquery);
    _acconfig.isGuest = guestUsage;
    if (!guestUsage) {
        var token = $('#token').val();
        _acconfig.serverInfo.token = token;
    }

    if (!enableDev) {
        _acconfig.serverInfo.hostName = clusterIP + ":8082";
    } else {
        _acconfig.serverInfo.hostName = clusterIP;
    }
    _acconfig.serverInfo.isSecure = true;
    _acconfig.enabled = true;
    var _AgentControllerClient = new AvayaCustomerInteractionUtilitiesClient(_acconfig);
    _AgentControllerClient.registerlogger(window.console);
    _acinstance = _AgentControllerClient.createCustomerInteractionUtilitiesService(_acconfig);
}

function createInstanceWithoutAuthorization() {
    var clusterIP = $('#clusterIP').val();
    var authServiceIP = $("#authClusterIp").val();
    resetResponse();

    _acconfig = new AvayaCustomerInteractionUtilitiesClient.Config.AcConfiguration();
    console.info('agent controller Engine Load Complete');
    console.info('[jQuery]: ' + $().jquery);
    _acconfig.isGuest = true;
    _acconfig.serverInfo.hostName = clusterIP;
    _acconfig.serverInfo.authorisationHost = authServiceIP;
    _acconfig.serverInfo.isSecure = true;
    _acconfig.enabled = true;
    var _AgentControllerClient = new AvayaCustomerInteractionUtilitiesClient(_acconfig);
    _AgentControllerClient.registerlogger(window.console);
    _acinstance = _AgentControllerClient.createCustomerInteractionUtilitiesService(_acconfig);
}

function resetRequestDetails() {
    $('#requestMethodName').text('');
    $('#requestBody').text('');

    if (document.getElementById('requestDetail')) {
        document.getElementById('requestDetail').style.display = 'none';
    }
    document.getElementById('progressDiv').style.display = 'none';
}

function resetResponse() {
    $('#responseMessageSuccess').text('');
    $('#responseMessageError').text('');
    $('#responseMessageErrorCode').text('');
    if (document.getElementById('responseAlertSuccess')) {
        document.getElementById('responseAlertSuccess').style.display = 'none';
    }
    if (document.getElementById('responseAlertError')) {
        document.getElementById('responseAlertError').style.display = 'none';
    }
}

/**
 * Show the request details for debugging purposes
 * @param {type} methodName
 * @param {type} requestBody
 * @returns {undefined}
 */
function requestDetails(methodName, requestBody) {
    resetRequestDetails();
    $('#requestMethodName').text(methodName);
    document.getElementById('requestBodyLabel').style.display = 'block';
    if (requestBody === "") {
        document.getElementById('requestBodyLabel').style.display = 'none';
    }
    $('#requestBody').text(requestBody);
    document.getElementById('requestDetail').style.display = 'block';
    $('#progressMessage').text('Processing...');
    document.getElementById('progressBar').className = 'progress-bar progress-bar-info progress-bar-striped active';
    document.getElementById('progressDiv').style.display = 'block';
}

function onSuccess(response) {
    if (response instanceof Object)
    {
        $('#response').val(JSON.stringify(response));
        $('#responseMessageSuccess').text(JSON.stringify(response));
    } else {
        $('#response').val(response);
        $('#responseMessageSuccess').text(response);
    }
    document.getElementById('responseAlertSuccess').style.display = 'block';
    $('#progressMessage').text('Complete');
    document.getElementById('progressBar').className = 'progress-bar progress-bar-success';
}
;

function onFailure(error) {

    var err = error._reason.responseText;
    var requestType = "Request";
    console.error(requestType + ' FAILED: ' + err);
    if (err === "") {
        err = "Connection to agent controller Failed. Please ensure IP has been set or check connection";
    } else {
        $('#responseMessageErrorCode').text(error._reason.status);
    }
    $('#responseMessageError').text(err);
    document.getElementById('responseAlertError').style.display = 'block';
    $('#progressMessage').text('Failed');
    document.getElementById('progressBar').className = 'progress-bar progress-bar-danger';
}
;


function deleteAttachmentByWorkrequestIdInteractionId() {
    var workRequestId = $('#deleteAttachmentByworkrequestId').val();
    var interactionId = $('#deleteAttachmentByInteractionId').val();
    var attachmentId = $('#deleteAttachmentByattachmentId').val();
    var fail_message = 'Error deleting attachment.The attachment may already have been removed.';
    var success_message = 'Attachment has been deleted.';

    _fail_message = fail_message;
    _success_message = success_message;

    this.createInstanceWithoutAuthorization();
    getAndSetSecureConnection();
    _acinstance.deleteAttachmentByWorkRequestIdInteractionId(workRequestId, interactionId, attachmentId).then(delete_success, delete_failure);

}

function cancelEmailByWorkrequestIdInteractionId() {
    var workRequestId = $('#cancelEmailByworkrequestId').val();
    var interactionId = $('#cancelEmailByInteractionId').val();
    var fail_message = 'Error cancelling email with attachment.The email may already have been cancelled.';
    var success_message = 'Email with attachment has been cancelled. ';

    _fail_message = fail_message;
    _success_message = success_message;

    this.createInstanceWithoutAuthorization();
    getAndSetSecureConnection();
    _acinstance.cancelEmailWithAttachmentByWorkRequestIdInteractionId(workRequestId, interactionId).then(delete_success, delete_failure);
}

function delete_success(status) {
    
    $('#responseMessageSuccess').text(_success_message+" Status: "+status );
    document.getElementById('responseAlertSuccess').style.display = 'block';
    $('#progressMessage').text('Complete');
    document.getElementById('progressBar').className = 'progress-bar progress-bar-success';
}
function delete_failure(error) {
    console.log("Fail " + error);
    $('#responseMessageError').text(error);
    document.getElementById('responseAlertError').style.display = 'block';
    $('#progressMessage').text('Failed');
    document.getElementById('progressBar').className = 'progress-bar progress-bar-danger';

}

function generateToken() {
    var scope = $('#scope').val();
    var username = $('#username').val();
    var password = $('#password').val();

    this.createInstanceWithoutAuthorization();

    var onTokenSuccess = function (response) {
        var generatedToken = response.token;
        $('#token').val(generatedToken);
        $('#responseMessageSuccess').text(generatedToken);
        document.getElementById('responseAlertSuccess').style.display = 'block';
    };

    var onTokenFailure = function (error) {
        var err = error._reason.responseText;
        console.error('Token Generatation FAILED: ' + err);
        $('#token').val(err);
        $('#responseMessageError').text(err);
        $('#responseMessageErrorCode').text(error._reason.status);
        document.getElementById('responseAlertError').style.display = 'block';
    };

    console.log (scope, username, password);
    _acinstance.generateToken(scope, username, password).then(onTokenSuccess, onTokenFailure);

}


function getCustomerHistoryByTranscriptId() {
    var transcriptId = $('#getCustomerHistoryByTranscriptId').val();

    requestDetails('getCustomerHistoryByTranscriptId', "");
    this.createInstance();
    _acinstance.getCustomerHistoryByTranscriptId(transcriptId).then(onSuccess, onFailure);
}

function getCustomerHistoryByUserDetails() {
    var userInput = {};
    if ($('#getCustomerHistoryByUserEmail').val() !== '')
    {
        userInput.email = $('#getCustomerHistoryByUserEmail').val();
    }
    if ($('#getCustomerHistoryByToAddress').val() !== '')
    {
        userInput.toAddress = $('#getCustomerHistoryByToAddress').val();
    }
    if ($('#getCustomerHistoryByStartDate').val() !== '')
    {
        userInput.startDate = $('#getCustomerHistoryByStartDate').val();
    }
    if ($('#getCustomerHistoryByEndDate').val() !== '')
    {
        userInput.endDate = $('#getCustomerHistoryByEndDate').val();
    }
    if ($('#getCustomerHistoryByKeyword').val() !== '')
    {
        userInput.keyword = $('#getCustomerHistoryByKeyword').val();
    }
    requestDetails('getCustomerHistoryByUserDetails', "");
    this.createInstance();
    _acinstance.getCustomerHistoryByUserDetails(userInput, {}, 0, 20).then(onSuccess, onFailure);
}


function getCustomerSearchResult() {
    var jsonObj = {};
    if ($('#getCustomerSearchResult').val() !== '')
    {
        jsonObj = JSON.parse($('#getCustomerSearchResult').val());
    }
    
    requestDetails('getCustomerSearchResult', "");
    this.createInstance();
    _acinstance.getCustomerSearchResult(jsonObj).then(onSuccess, onFailure);
}

function getCustomerDetails() {
    var customerId = $('#getCustomerDetails').val();

    requestDetails('getCustomerDetails', "");
    this.createInstance();
    _acinstance.getCustomerDetails(customerId).then(onSuccess, onFailure);
}

function getCustomerHistoryByContactId() {
    var contactID = $('#getCustomerHistoryByContactId').val();

    requestDetails('getCustomerHistoryByContactId', "");
    this.createInstance();
    _acinstance.getContactDetails(contactID).then(onSuccess, onFailure);
}

function getUploadAttachmentsByWorkrequestIdInteractionIdLocale() {
    var workRequestId = $('#getUploadAttachmentsByWorkrequestId').val();
    var interactionId = $('#getUploadAttachmentsByInteractionId').val();
    var locale = $('#getUploadAttachmentsByLocale').val();

    var enableDev = ($("#enableDev").is(':checked') ? false : true);
    requestDetails('getUploadAttachmentsByWorkrequestIdInteractionIdLocale', "");
    this.createInstance();
    if (!enableDev) {
        _acinstance.getUploadAttachmentsByWorkrequestIdInteractionIdLocaleDev(workRequestId, interactionId, locale).then(onSuccess, onFailure);
    } else {
        _acinstance.getUploadAttachmentsByWorkrequestIdInteractionIdLocale(workRequestId, interactionId, locale).then(onSuccess, onFailure);
    }
}


function getAllTemplates()
{
	 requestDetails('getAllTemplates', "");
	 this.createInstance();
	 _acinstance.getAllTemplates().then(onSuccess, onFailure);
}

function getTemplateById()
{
	 var templateID = $('#getTemplateById').val();
	    requestDetails('getTemplateById', "");
	    this.createInstance();
	    _acinstance.getTemplateById(templateID).then(onSuccess, onFailure);
}

function insertTemplateAttachments()
{
	var templateID = $('#getUploadTemplateAttachmentsByTemplateId').val();
	var workRequestID = $('#getUploadTemplateAttachmentsByWorkrequestId').val(); 
	var interactionID = $('#getUploadTemplateAttachmentsByInteractionId').val();
	
	    requestDetails('insertTemplateAttachments', "");
	    this.createInstance();
	    _acinstance.insertTemplateAttachments(workRequestID, interactionID, templateID).then(onSuccess, onFailure);
}

function getTemplateAttachmentById()
{
	 var attachmentID = $('#getTemplateAttachmentById').val();
	    requestDetails('getTemplateAttachmentById', "");
	    this.createInstance();
	    _acinstance.getTemplateAttachmentById(attachmentID).then(onSuccess, onFailure);
}

function uploadAttachment() 
{
    var workRequestID = $('#fileUploadWorkRequestId').val(); 
    var interactionID = $('#fileUploadInteractionId').val();
    var files = $("#fileUploadInput")[0].files;
    var formData = new FormData();
    
    for (var i = 0; i < files.length; i++) {
        var key = "file-" + i;
        formData.append(key, files[i], files[i].name);
    }
    
    var body = {
        "workRequestId" : workRequestID,
        "interactionId" : interactionID,
        "formData" : formData
    };
    
    requestDetails('uploadAttachments', JSON.stringify(body));
    this.createInstance();
    
    _acinstance.uploadAttachment(workRequestID, interactionID, files).then(onSuccess, onFailure);
            
}

function requestUploadData() {
    
    var workRequestID = $('#fileUploadWorkRequestId').val(); 
    var interactionID = $('#fileUploadInteractionId').val();
    
    var json = {
        "workRequestid" : workRequestID,
        "interactionId" : interactionID
    };
    
    requestDetails("requestUploadData", JSON.stringify(json));
    this.createInstance();
    
    _acinstance.requestMaxFileSize(workRequestID, interactionID).then(onSuccess, onFailure);
}


function getAndSetSecureConnection() {
    var enableSecure = ($("#enableSecure").is(':checked') ? true : false);

    if (!enableSecure) {
        _acconfig.serverInfo.isSecure = false;
    } else {
        _acconfig.serverInfo.isSecure = true;
    }
    console.log(_acconfig.serverInfo.isSecure);
}

function openRequest(evt, reqName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(reqName).style.display = "block";
    evt.currentTarget.className += " active";
}
;


/* Set the width of the side navigation to 250px */
function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
}


/* Set the width of the side navigation to 0 */
function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
}

function saveLabel(element) {
    var txt = $(this).val();
    $(this).replaceWith("<span id='" + element + "' class='" + element.class + "' ></span>");
    if (txt !== '') {
        $("#" + element).text(txt);
    } else {
        $("#" + element).text('"+element.default+"');
    }
}

$(document).ready(function(){
    var version = getVersion();
    $("#version").text("SDK Version: " + version);
});

$(document).on("click", "span.queryParams", function () {
    var clickedID = $(this).attr('id');
    var txt = $("#" + clickedID).text();
    var pl = $(this).attr('title');
    if (txt === '') {
        txt = $("#" + clickedID).val();
    }
    $("#clearField").hide();
    $("#" + clickedID).replaceWith("<input class='queryParams queryInput' id='" + clickedID + "' maxlength='30' type='text' /><span id='clearField' class='glyphicon glyphicon-remove queryInput' onClick='clearLabel(this, " + clickedID + ");' ></span></span>");
    $("#" + clickedID).attr("placeholder", pl);
    $("#" + clickedID).val(txt);
});

function clearLabel(self, obj) {
    var objId = obj.id;
    var selfId = self.id;
    $("#" + objId).val('');
    $("#" + selfId).remove();
    $("#" + objId).blur();
}

$(document).on("blur", "input.queryInput", function () {

    var blurredID = this.id;
    var txt = $(this).val();
    var pl = $(this).attr('placeholder');
    if (txt !== '' && txt !== pl) {
        if (!(blurredID.includes('input'))) {
            $(this).replaceWith("<span class='label label-success queryParams' id='" + blurredID + "-input' ><span class='glyphicon glyphicon-ok' > " + txt + " </span></span>");
        } else {
            $(this).replaceWith("<span class='label label-success queryParams' id='" + blurredID + "' ><span class='glyphicon glyphicon-ok' > " + txt + " </span></span>");
        }

        $("#" + blurredID + "-input").attr("title", pl);
    } else {
        $(this).replaceWith("<span class='label label-default queryParams' id='" + blurredID + "' ></span>");
        $("#" + blurredID).text(pl);
        $("#" + blurredID).attr("title", pl);
    }
    $("#clearField").remove();
});

