////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// 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 = $('#authorization').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, 'CustomerManagement');
}

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, 'CustomerManagement');
}

// function buildContextData(data, contextId, alias1, alias2, alias3, groupId, tenantId){
// if (groupId !== ""){
// var newData = data.replace(/^\{/gi, "");
// data="{\"groupId\":\""+groupId+"\"," + newData;
// }
// if (tenantId !== ""){
// var newData = data.replace(/^\{/gi, "");
// data="{\"tenantId\":\""+tenantId+"\"," + newData;
// }
// if (contextId !== ""){
// var newData = data.replace(/^\{/gi, "");
// data="{\"contextId\":\""+contextId+"\"," + newData;
// }
// if (alias1 !== "" || alias2 !== "" || alias3 !== "") {
// var newData = data.replace(/^\{/gi, "");
// var aliases = [];
// if (alias1 !=="") {
// aliases.push(alias1);
// }
// if (alias2 !=="") {
// aliases.push(alias2);
// }
// if (alias3 !=="") {
// aliases.push(alias3);
// }
// data="{\"alias\":"+JSON.stringify(aliases)+"," + newData;

// }
// return data;

// }
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 Management Failed. Please ensure IP has been set or check connection";
            $('#responseMessageError').text(err);
        } else {
            $('#responseMessageErrorCode').text(error._reason.status);
        }
        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';
    };

    _csinstance.generateToken(scope, username, password).then(onTokenSuccess, onTokenFailure);

}

function verifyCustMgtStatus() {
    requestDetails('verifyCustMgtStatus', "");
    this.createInstance();
    _csinstance.getCustomerManagementStatus().then(onSuccess, onFailure);
}

function getCustomerRecord() {
    var custId = $('#custId-GetCustomerRecord-input').text().trim();
    var crmId = $('#crmId-GetCustomerRecord-input').text().trim();
    var phone = $('#phone-GetCustomerRecord-input').text().trim();
    var email = $('#email-GetCustomerRecord-input').text().trim();
    var social = $('#social-GetCustomerRecord-input').text().trim();
    var platform = $('#platform-GetCustomerRecord-input').text().trim();
    var accountId = $('#accountId-GetCustomerRecord-input').text().trim();
    var accountType = $('#accountType-GetCustomerRecord-input').text().trim();
    var authorization = $('#authorization').val();
    // var authorization=$('#authorization-GetCustomerRecord-input').text().trim();
    var summaryDataOnly = '';
    if ($("#summaryDataOnly-GetCustomerRecord").is(':checked')) {
        summaryDataOnly = 'true';
    }

    requestDetails('getCustomerRecord', "");
    this.createInstance();
    _csinstance.getCustomerRecord(custId, crmId, phone, email, social, platform, accountId, accountType, summaryDataOnly, authorization).then(onSuccess, onFailure);
}

function getCustomerId() {
    var crmId = $('#crmId-GetCustomerId-input').text().trim();
    var phone = $('#phone-GetCustomerId-input').text().trim();
    var email = $('#email-GetCustomerId-input').text().trim();
    var social = $('#social-GetCustomerId-input').text().trim();
    var platform = $('#platform-GetCustomerId-input').text().trim();
    var accountId = $('#accountId-GetCustomerId-input').text().trim();
    var accountType = $('#accountType-GetCustomerId-input').text().trim();

    requestDetails('getCustomerId', "");
    this.createInstance();
    _csinstance.getCustomerId(crmId, phone, email, social, platform, accountId, accountType).then(onSuccess, onFailure);
}


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

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

function getCustomerJourneyOnCustomer() {
    var customerId = $('#customerId-GetCustomerJourneyOnCustomer').val();
    var topic = $('#topic-GetCustomerJourneyOnCustomer-input').text().trim();

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

function getCustomerDetails() {
    var workrequestId = $('#workrequestId-GetCustomerDetails-input').text().trim();
    var customerId = $('#customerId-GetCustomerDetails-input').text().trim();

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

function getCustomerHistory() {
    var workrequestId = $('#workrequestId-GetCustomerHistory-input').text().trim();

    requestDetails('getCustomerHistory', "");
    this.createInstance();
    _csinstance.getCustomerHistory(workrequestId).then(onSuccess, onFailure);
}

function getCustomerHistoryOnCustomer() {
    var customerId = $('#customerId-GetCustomerHistoryOnCustomer').val();

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

function createJourneyElement() {
    var elementData = $('#elementData-CreateJourneyElement').val();
    // var authHeader=$('#authHeader-CreateJourneyElement-input').text().trim();
    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 authHeader=$('#authHeader-UpdateJourneyElement-input').text().trim();
    var authorization = $('#authorization').val();

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

function registerCallbacksUI() {

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

    var key = null;

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

    });
}

function cleanup() {
    $('#contextData').val('');
}

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 editLabel(element) {
    var txt = $("#" + element).text();
    if (txt === '') {
        txt = $("#" + element).val();
    }
    $("#" + element).replaceWith("<input id='" + element + "' maxlength='30' type='text' />");
    $("#" + element).val(txt);
}

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).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();
});

