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

var _iframeId = 'iframeDiv';
var _csinstance = null;
var _useSecure = false;

function contextStoreInit() {

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

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////// Validate URL parameters and fork the code workflow  ////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    registerCallbacksUI();

}

function toggleUseSecure() {
    if ($("#useSecure").is(':checked')) {
        _useSecure = true;
    } else {
        _useSecure = false;
    }
}

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

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

    _csconfig = new AvayaDataStoreClient.Config.CsConfiguration();
    console.info('Data Store Engine Load Complete');
    console.info('[jQuery]: ' + $().jquery);
    _csconfig.isGuest = guestUsage;
    if (!guestUsage) {
        var token = $('#token').val();
        _csconfig.serverInfo.token = token;
    }
    _csconfig.serverInfo.hostName = clusterIP;
    _csconfig.serverInfo.isSecure = _useSecure;
    _csconfig.enabled = true;
    var _dataStoreClient = new AvayaDataStoreClient(_csconfig);
    _dataStoreClient.registerlogger(window.console);
    _csinstance = _dataStoreClient.createDataStoreService(_csconfig, 'CustomerJourney');
}

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

    _csconfig = new AvayaDataStoreClient.Config.CsConfiguration();
    console.info('Context Store Engine Load Complete');
    console.info('[jQuery]: ' + $().jquery);
    _csconfig.isGuest = true;
    _csconfig.serverInfo.hostName = clusterIP;
    _csconfig.serverInfo.isSecure = _useSecure;
    _csconfig.enabled = true;
    var _dataStoreClient = new AvayaDataStoreClient(_csconfig);
    _dataStoreClient.registerlogger(window.console);
    _csinstance = _dataStoreClient.createDataStoreService(_csconfig, 'CustomerJourney');
}

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';
    }
}

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) {
    $('#response').val(JSON.stringify(response));
    $('#responseMessageSuccess').text(JSON.stringify(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.indexOf("nodes") >= 0) {
        $('#response').val(JSON.stringify(err));
        $('#responseMessageSuccess').text(err);
        document.getElementById('responseAlertSuccess').style.display = 'block';
        $('#progressMessage').text('Complete');
        document.getElementById('progressBar').className = 'progress-bar progress-bar-success';
    } else {
        if (err === "") {
            err = "Connection to Customer Journey Failed. Please ensure IP has been set or check connection";
            $('#responseMessageError').text(err);
        } else {
            $('#responseMessageErrorCode').text(error._reason.status);
            $('#responseMessageError').text(error._message);
        }
        document.getElementById('responseAlertError').style.display = 'block';
        $('#progressMessage').text('Failed');
        document.getElementById('progressBar').className = 'progress-bar progress-bar-danger';
    }
}

function getCustomerJourney() {
    var customerId = $('#customerId-GetCustomerJourney').val();
    var topic = $('#topic-GetCustomerJourney-input').text().trim();
    var authorization = $('#authorization').val();

    requestDetails('getCustomerJourney', "");
    this.createInstance();
    _csinstance.getCustomerJourney(customerId, topic, authorization).then(onSuccess, onFailure);
}

function getCustomerJourneyViaElementId() {
    var elementId = $('#elementId-GetCustomerJourneyViaElementId').val();
    var topic = $('#topic-GetCustomerJourneyViaElementId-input').text().trim();
    var before = $('#before-GetCustomerJourneyViaElementId-input').text().trim();
    var authorization = $('#authorization').val();

    requestDetails('getCustomerJourneyViaElementId', "");
    this.createInstance();
    _csinstance.getCustomerJourneyViaElementId(elementId, topic, before, authorization).then(onSuccess, onFailure);
}

function getCustomerJourneyWithAdminDataViaElementId() {
    var elementId = $('#elementId-GetCustomerJourneyWithAdminDataViaElementId').val();
    var topic = $('#topic-GetCustomerJourneyWithAdminDataViaElementId-input').text().trim();
    var before = $('#before-GetCustomerJourneyWithAdminDataViaElementId-input').text().trim();
    var authorization = $('#authorization').val();

    requestDetails('getCustomerJourneyWithAdminDataViaElementId', "");
    this.createInstance();
    _csinstance.getCustomerJourneyWithAdminDataViaElementId(elementId, topic, before, authorization).then(onSuccess, onFailure);
}

function getLastJourneyElement() {
    var elementId = $('#elementId-GetLastJourneyElement').val();
    var topic = $('#topic-GetLastJourneyElement-input').text().trim();
    var before = $('#before-GetLastJourneyElement-input').text().trim();
    var authorization = $('#authorization').val();

    requestDetails('getLastJourneyElement', "");
    this.createInstance();
    _csinstance.getLastJourneyElement(elementId, topic, before, authorization).then(onSuccess, onFailure);
}

function getCustomerJourneyViaAccountId() {
    var accountId = $('#accountId-GetCustomerJourneyViaAccountId').val();
    var topic = $('#topic-GetCustomerJourneyViaAccountId-input').text().trim();
    var authorization = $('#authorization').val();

    requestDetails('getCustomerJourneyViaAccountId', "");
    this.createInstance();
    _csinstance.getCustomerJourneyViaAccountId(accountId, topic, authorization).then(onSuccess, onFailure);
}

function createJourneyElement() {
    var elementData = $('#elementData-CreateJourneyElement').val();
    var authorization = $('#authorization').val();

    requestDetails('createJourneyElement', "");
    this.createInstance();
    _csinstance.createJourneyElement(elementData, authorization).then(onSuccess, onFailure);
}

function updateJourneyElement() {
    var elementId = $('#elementId-UpdateJourneyElement').val();
    var elementData = $('#elementData-UpdateJourneyElement').val();
    var authorization = $('#authorization').val();

    requestDetails('updateJourneyElement', "");
    this.createInstance();
    _csinstance.updateJourneyElement(elementId, elementData, authorization).then(onSuccess, onFailure);
}

function updateAgentNote() {
    var interactionId = $('#interactionId-UpdateAgentNote').val();
    var agentNote = $('#agentNote-UpdateAgentNote').val();
    var authorization = $('#authorization').val();

    requestDetails('updateAgentNote', "");
    this.createInstance();
    _csinstance.updateAgentNote(interactionId, agentNote, authorization).then(onSuccess, onFailure);
}

function updateIdentifiers() {
    var elementId = $('#elementId-UpdateIdentifiers').val();
    var identifiersData = $('#identifiersData-UpdateIdentifiers').val();
    var authorization = $('#authorization').val();

    requestDetails('updateIdentifiers', "");
    this.createInstance();
    _csinstance.updateIdentifiers(elementId, identifiersData, authorization).then(onSuccess, onFailure);
}

function registerCallbacksUI() {

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////// Callbacks from GUI //////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    var key = null;

    //Request new context creation
    $("#avCreateBtn").click(function () {
        this.createContext();

    });
}

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";
}

$(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='" + clickedID + "_clearField' class='glyphicon glyphicon-remove queryInput' title='" + clickedID + "' onClick='clearLabel(this);' ></span></span>");
    $("#" + clickedID).attr("placeholder", pl);
    $("#" + clickedID).val(txt);
});

function clearLabel(self) {
    var str = $(self).attr('id');
    var objId = str.slice(0, -"_clearField".length);
    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);
    }
    $("#" + blurredID + "_clearField").remove();
});

