"use strict";
var DatabaseConnectionXML;
var DatabaseXML;
var SelectedLogin = '<configuration />';
var SelectedDatabase;
var loggedOnUser;
var loggedOnDomain;
var UndoTimeout;
var DeleteConfig;
var WebApiHostUrl = window.location.origin + '/api/AprimaClient/'

function showInfo(message) { alert(message); }

function LoadBuildString() {
    var clientBuild = ("Client Build: " + new URLSearchParams(window.location.search).get('build'));
    console.log(clientBuild);
    document.getElementById("Build").innerText = clientBuild;
    document.getElementById("LoginModalTitle").innerText = ProductName + " - Login"
    document.getElementById("Copyright").innerText = ProductCopyright;
    document.getElementById("ErrorTitle").innerText = ProductName + " - Error"
};


//function LoadBuildString() {
//    fetch(WebApiHostUrl + 'GetBuildString')
//        .then(response => response.text())
//        .then((data) => {
//            xmlBuild = new window.DOMParser().parseFromString(data, "text/xml");
//            console.log(xmlBuild);
//            document.getElementById("Build").innerText = xmlBuild.getElementsByTagName('Name')[0].innerHTML;
//            document.getElementById("LoginModalTitle").innerText = xmlBuild.getElementsByTagName('Name')[0].innerHTML + " - Login"
//            document.getElementById("Copyright").innerText = xmlBuild.getElementsByTagName('Copyright')[0].innerHTML;
//            document.getElementById("ErrorTitle").innerText = xmlBuild.getElementsByTagName('Name')[0].innerHTML + " - Login Failed"
//        })
//        .catch(function (error) { console.log(error) });
//};



// this function loads the fields in the UserInformation form 
function GetSavedLoginAPI() {
    // GetSavedLogin loads the DatabaseConnection.xml file which has the users favorite logins  
    return fetch(WebApiHostUrl + 'GetSavedLogin')
    .then(response => response.text())
    .then((data) => {
        DatabaseConnectionXML = new window.DOMParser().parseFromString(data, "text/xml");
        //find and save the loggedinuser information
        var findconfig = $(DatabaseConnectionXML).find("configuration[database='00000000-0000-0000-0000-000000000000']");
        loggedOnUser = findconfig[0].attributes['Username'].value;
        loggedOnDomain = findconfig[0].attributes['Domain'].value;
//        var configs = DatabaseConnectionXML.getElementsByTagName('configuration');
//        for (var i = 0; i < configs.length; i++) {
//            if (configs[i].attributes['section'].value === "") {
        var config = $(DatabaseConnectionXML).find("configuration[section='']");
        if (config.length > 0) {
            document.getElementById("user").value = config[0].attributes['Username'].value;
            document.getElementById("domain").value = config[0].attributes['Domain'].value;
            var SelectedName = config[0].attributes['name'].value;
            document.getElementById("findDatabase").innerText = "Database: " + SelectedName;
            SelectedLogin = config[0].outerHTML;
            SelectedDatabase = config[0].attributes['database'].value
            console.log("SelectedLogin " + SelectedName + " - " + SelectedLogin);
            $('#dxsection').val(SelectedDatabase)
            document.activeElement.blur();
            $('#useloginuser').focus();
            if (config[0].attributes['UseCurrentUser'].value === "True") { //uppercase True in the xml
                document.getElementById("useloginuser").checked = false;  //set it !True so we can click() below
            } else {
                document.getElementById("useloginuser").checked = true;
            }
            document.getElementById("useloginuser").click();
        }
//            }
//        };
        if (document.getElementById("findDatabase").innerText === "Database: ") {
            $('#Configuration').click();
        }
    })
    .catch (function (error) { console.log(error) });
};


function GetDatabaseListAPI() {
    fetch(WebApiHostUrl + 'GetDatabaseList')
    // GetDatabaseList loads the Database.xml file which has all the logins saved on this computer
        .then(response => response.text())
        .then((data) => {
            DatabaseXML = new window.DOMParser().parseFromString(data, "text/xml");
            LoadSearchModal();
        })
        .catch(function (error) { console.log(error) });
};

function LoadSearchModal() {
    var configs = DatabaseXML.getElementsByTagName('configuration');
    var tab = ``;
    //SearchDatabaseList() depends on the layout of this table
    console.log("configs.length " + configs.length);
    for (var i = 0; i < configs.length; i++) {
        var name = configs[i].attributes['name'].value;
        var section = configs[i].attributes['section'].value;
        tab += `<tr onclick="ClickCurrentDatabase('${section}')">
                <td><div class="form-check form-check-inline">
				    <input class="form-check-input" type="radio" name="RadioDatabaseList" id="${section}" value="${name}">
				</div></td>
                <td>${configs[i].attributes['externalid'].value}</td>
                <td><a href="" onclick="UpdateSavedLogin('${section}','${name}')" data-dismiss="modal">${name}</a></td>
                <td>${configs[i].attributes['applicationserver'].value}</td>
                <td>${configs[i].attributes['applicationserverport'].value}</td>
                <td hidden>${configs[i].attributes['sqlserver'].value}</td>
                <td hidden>${configs[i].attributes['serverdatabase'].value}</td>
                <td>${(configs[i].hasAttribute('clientid') === false) ? '' : configs[i].attributes['clientid'].value}</td>
                <td hidden>${configs[i].attributes['localAppServer'].value}</td>
                <td hidden>${configs[i].attributes['applicationlocalport'].value}</td>
                <td hidden>${(configs[i].hasAttribute('userelay') === false) ? 'false' : configs[i].attributes['userelay'].value}</td>
                <td hidden>${configs[i].attributes['local'].value}</td>
                <td hidden>${section}</td>
                </tr>`;
    }
    document.getElementById("DatabaseList").innerHTML = tab;
    if (configs.length < 50) { sortTable(); }
    document.getElementById("databasecount").innerHTML = `Items found: ${i}`;
    var selected = document.getElementById(SelectedDatabase);
    if (selected === null && document.getElementsByName("RadioDatabaseList") > 0) {
        selected = document.getElementsByName("RadioDatabaseList")[0];
    }
    if (selected !== null) {
        selected.scrollIntoView({ block: "center" });
        selected.click();
        document.getElementById(SelectedDatabase).click();
    }
}

function ClickCurrentDatabase(section) {
    document.getElementById(section).click();
    console.log("Current row: " + section);
};

function UpdateSavedLogin(section, name) {
//    search DatabaseConnection for selection, use settings if found otherwise set to usecurrentuser  LogonDialog.cs findDatabase_SelectionChanged
    var found = false, username, domain;
    var configs = DatabaseConnectionXML.getElementsByTagName('configuration');
    for (var i = 0; i < configs.length; i++) {
        if (configs[i].attributes['section'].value === section) {
            document.getElementById("user").value = configs[i].attributes['Username'].value;
            document.getElementById("domain").value = configs[i].attributes['Domain'].value;
            //if (configs[i].attributes['UseCurrentUser'].value == 'True') { //uppercase True in the xml
            if ((document.getElementById("useloginuser").checked === true) !==
                (configs[i].attributes['UseCurrentUser'].value === "True")) {
                //toggle the checkbox if needed
                document.getElementById("useloginuser").click();
                //document.getElementById("Login").focus;
            }
            document.getElementById("findDatabase").innerText = "Database: " + configs[i].attributes['name'].value;
            console.log('SelectedLogin')
            console.log(configs[i].outerHTML);
            SelectedLogin = configs[i].outerHTML;
            SelectedDatabase = configs[i].attributes['database'].value
            found = true;
            break;
        }
        else if (configs[i].attributes['name'].value === "LoggedOnUser") {
            username = configs[i].attributes['Username'].value;
            domain = configs[i].attributes['Domain'].value;
        }
    }
    if (found === false) {
        document.getElementById("findDatabase").innerText = "Database: " + name;
        document.getElementById("user").value = username;
        document.getElementById("domain").value = domain;
        if (document.getElementById("useloginuser").checked === false) {
            document.getElementById("useloginuser").click();
        }
        var login = new window.DOMParser().parseFromString(SelectedLogin, "text/xml");
        login.children[0].setAttribute('name', name);
        login.children[0].setAttribute('section', section);
        login.children[0].setAttribute('database', section);
        login.children[0].setAttribute('Username', username);
        login.children[0].setAttribute('Domain', domain);
        login.children[0].setAttribute('UseCurrentUser', "True");
        login.children[0].setAttribute('Password', "");
        SelectedLogin = login.children[0].outerHTML;
        SelectedDatabase = section;
    }
}

var validationErrorField;
function validate(valuename) {
    var valueitem = document.getElementById(valuename);
    if (valueitem === null || valueitem.value === "") {
        if (validationErrorField === null) { validationErrorField = valueitem; }
        document.getElementById(valuename).classList.add("error");
        document.getElementById("err-" + valuename).classList.add("visible");
        return false;
    }
    return true;
}
function clearError(erroritem) {
    document.getElementById(erroritem.id).classList.remove("error");
    document.getElementById("err-" + erroritem.id).classList.remove("visible");
}

function CallLogonDialogAPI(proceed) {
    var postbody = `<root>Cancel</root>`;
    if (proceed === null) { alert('call Logon worked.'); return; }
    if (proceed === true) {
        var logindata = new window.DOMParser().parseFromString(SelectedLogin, "text/xml");
        //required fields checking
        validationErrorField = null;
        var valuename = "user";
        if (validate(valuename)) { logindata.children[0].setAttribute('Username', document.getElementById(valuename).value); }
        if (document.getElementById("useloginuser").checked === false) {
            valuename = "password";
            if (validate(valuename)) { logindata.children[0].setAttribute('Password', document.getElementById(valuename).value); }
        }
        logindata.children[0].setAttribute('Domain', document.getElementById("domain").value);
        logindata.children[0].setAttribute('UseCurrentUser', document.getElementById("useloginuser").checked);

        if (validationErrorField !== null) {
            document.activeElement.blur();
            validationErrorField.focus();
            return;  }
        postbody = `<root>${logindata.children[0].outerHTML}</root>`;
    }
    fetch(WebApiHostUrl + 'CallLogonDialog',
        {
            method: 'POST',
            body: postbody,
            headers: {
                'Content-Type': 'text/xml; charset=UTF-8',
                'Accept': '*/*',
                'Accept-Encoding': 'gzip, deflate, br'
            }
        })
        .then(response => response.text())
        .then((data) => {
            if (data === "") {  //this is Cancel
                return;
            };
            var xmlMessage = new window.DOMParser().parseFromString(data, "text/xml");
            console.log("Logon Message");
            console.log(xmlMessage);
            var Message = xmlMessage.getElementsByTagName('Message')[0].innerHTML;
            console.log(Message);
            if (xmlMessage !== null && Message !== 'Cancel') {
                //Trigger the error modal
                CallErrorModal(Message);
            }
        })
        .catch(function (error) { console.log(error) });
};



function SearchDatabaseList() {
    var input = document.getElementById("searchdatabaselist");
    var filter = input.value.toUpperCase();
    var table = document.getElementById("DatabaseList");
    var tr = table.getElementsByTagName("tr");
    var count = 0
    // Loop through all table rows, and hide those who don't match the search query
    for (var i = 0; i < tr.length; i++) {
        var ID = tr[i].getElementsByTagName("td")[1];  //1 is ID
        if (ID) {
            var IDValue = ID.textContent || ID.innerText;
            var IDValueFound = IDValue.toUpperCase().indexOf(filter) > -1
        }
        var Name = tr[i].getElementsByTagName("td")[2];  //2 is Name
        if (Name) {
            var NameValue = Name.textContent || Name.innerText;
            var NameValueFound = NameValue.toUpperCase().indexOf(filter) > -1
        }
        var Appserver = tr[i].getElementsByTagName("td")[3];  //3 is applicationserver
        if (Appserver) {
            var AppserverValue = Appserver.textContent || Appserver.innerText;
            var AppserverValueFound = AppserverValue.toUpperCase().indexOf(filter) > -1
        }
        var Port = tr[i].getElementsByTagName("td")[4];  //4 is Port
        if (Port) {
            var PortValue = Port.textContent || Port.innerText;
            var PortValueFound = PortValue.toUpperCase().indexOf(filter) > -1
        }
        var Clientid = tr[i].getElementsByTagName("td")[7];  //7 is Clientid
        if (Clientid) {
            var ClientidValue = Clientid.textContent || Clientid.innerText;
            var ClientidValueFound = ClientidValue.toUpperCase().indexOf(filter) > -1
        }
        if (NameValueFound || IDValueFound || AppserverValueFound || PortValueFound || ClientidValueFound) {
            tr[i].style.display = "";
            count++;
        } else {
            tr[i].style.display = "none";
        }
    }
    document.getElementById("databasecount").innerHTML = `Items found: ${count}`;
}



//this loads the Database configuration edit modal
$(function () {
    $('#db-modal').modal({
        keyboard: true,
        backdrop: "static",
        show: false,
    }).on('shown.bs.modal', function (e) {
        var DBCommand = e.relatedTarget.dataset.modalCmd;
        $('#dxcommand').val(DBCommand);
        if (DBCommand === 'New') {
            document.activeElement.blur();
            $('#dxexternalid').focus();
            return;  }
        var CheckedRow = $(DatabaseList).find("tr input[type='radio']:checked");
        if (CheckedRow.length === 0) {  return;  }
        var id = CheckedRow.closest('tr').find('td:eq( 1 )').html();
        $('#dxexternalid').val(id);
        var name = CheckedRow.closest('tr').find('td:eq( 2 )')[0].textContent;
        $('#dxname').val(name);
        var dxapplicationserver = CheckedRow.closest('tr').find('td:eq( 3 )').html();
        $('#dxapplicationserver').val(dxapplicationserver);
        var dxport = CheckedRow.closest('tr').find('td:eq( 4 )').html();
        $('#dxport').val(dxport)
        var dxsqlserver = CheckedRow.closest('tr').find('td:eq( 5 )').html();
        $('#dxsqlserver').val(dxsqlserver)
        var dxdatabase = CheckedRow.closest('tr').find('td:eq( 6 )').html();
        $('#dxdatabase').val(dxdatabase)
        var dxclientid = CheckedRow.closest('tr').find('td:eq( 7 )').html();
        $('#dxclientid').val(dxclientid)
        var dxreplapplicationserver = CheckedRow.closest('tr').find('td:eq( 8 )').html();
        $('#dxreplapplicationserver').val(dxreplapplicationserver);
        var dxreplport = CheckedRow.closest('tr').find('td:eq( 9 )').html();
        $('#dxreplport').val(dxreplport)
        var userelay = CheckedRow.closest('tr').find('td:eq( 10 )').html();
        var local = CheckedRow.closest('tr').find('td:eq( 11 )').html();
        if (userelay === 'true') {
            $('#relaycheck').click();
        }
        else if (local === 'true') {
            $('#replicationcheck').click();
        }
        else {
            $('#maincheck').click();
        }
        var dxsection = CheckedRow.closest('tr').find('td:eq( 12 )').html();
        $('#dxsection').val(dxsection)
    });
});


function SaveDatabaseAPI(Config, cmd) {
    if (Config === null) { alert('Config is null'); return; }
    fetch(WebApiHostUrl + 'SaveDatabase?cmd='+ cmd,
        {
            method: 'POST',
            body: Config.outerHTML,
            headers: {
                'Content-Type': 'text/xml; charset=UTF-8',
                'Accept': '*/*',
                'Accept-Encoding': 'gzip, deflate, br'
            }
        })
        .then(response => response.text())
        .then((data) => {
            var xmlReply = new window.DOMParser().parseFromString(data, "text/xml");
            console.log("SaveDatabaseAPI Message  " + xmlReply.outerHTML);
            var Section = xmlReply.children[0].textContent;
            console.log(Section);
            if (cmd === "New") {  //new database element
                Config.setAttribute('section', Section);
                SelectedDatabase = Section;
            }
            LoadSearchModal();
        })
        .catch(function (error) { console.log(error) });
};


function SaveDatabase() {
    var config;
    var cmd = $('#dxcommand').val();
    console.log("cmd is " + cmd)
    //required fields checking
    validationErrorField = null;
    validate("dxname");
    if ($('#maincheck').prop('checked')) {
        validate("dxapplicationserver");
        validate("dxport");
    }
    if ($('#relaycheck').prop('checked')) {
        validate("dxclientid");
    }
    if ($('#replicationcheck').prop('checked')) {
        validate("dxapplicationserver");
        validate("dxport");
        validate("dxreplapplicationserver");
        validate("dxreplport");
    }
    if (validationErrorField !== null) {
        document.activeElement.blur();
        validationErrorField.focus();
        return;
    }
    var CheckedRow = $(DatabaseList).find("tr input[type='radio']:checked");        
    if (cmd === "New" || CheckedRow.length === 0) {  //new database element
        config = DatabaseXML.createElement("configuration");
        DatabaseXML.documentElement.appendChild(config);
        config.setAttribute('section', "");
        // this is set after the API call returns the GUID SelectedDatabase = section;
    }
    else if (cmd === "Modify") {
        var section = CheckedRow[0].id;
        SelectedDatabase = section;
        var findconfig = $(DatabaseXML).find("configuration[section='"+ section + "']");
        config = findconfig[0];
    }
    config.setAttribute('externalid', $('#dxexternalid').val());
    config.setAttribute('name', $('#dxname').val());
    config.setAttribute('applicationserver', $('#dxapplicationserver').val());
    config.setAttribute('applicationserverport', $('#dxport').val());
    config.setAttribute('sqlserver', $('#dxsqlserver').val());
    config.setAttribute('serverdatabase', $('#dxdatabase').val());
    config.setAttribute('inactive', "false");  //this is no longer needed for v19
    config.setAttribute('notes', "");
    config.setAttribute('localdatabase', "");  //this is no longer needed for v19
    config.setAttribute('local', $('#replicationcheck').is(':checked'));
    config.setAttribute('applicationlocalport', $('#dxreplport').val());
    config.setAttribute('localAppServer', $('#dxreplapplicationserver').val());
    config.setAttribute('localDBServer', "");  //this is no longer needed for v19
    config.setAttribute('userelay', $('#relaycheck').is(':checked'));
    config.setAttribute('clientid', $('#dxclientid').val());
    console.log(config.outerHTML)

    SaveDatabaseAPI(config, cmd);
    $('#db-modal').modal('hide');
};

function DeleteDatabase() {
    var CheckedRow = $(DatabaseList).find("tr input[type='radio']:checked");
    if (CheckedRow.length === 0) {
        clearTimeout(UndoTimeout);
        CallErrorModal("Select a database entry to delete.");
        return;
    }
    var section = CheckedRow[0].id;
    var findconfig = $(DatabaseXML).find("configuration[section='" + section + "']");
    if (findconfig.length === 0) {
        clearTimeout(UndoTimeout);
        CallErrorModal("Select a database entry to delete.");
        return;
    }
    var config = findconfig[0];
    console.log("Delete Database " + section)
    DeleteConfig = findconfig[0];     //save for Undo
    DatabaseXML.documentElement.removeChild(findconfig[0]);
    $('#dxcommand').val("Delete");
    LoadSearchModal();
};
function UndoDelete() {
    clearTimeout(UndoTimeout);
    if (DeleteConfig !== null) {
        DatabaseXML.documentElement.appendChild(DeleteConfig);    //replace with saved
        console.log("Undo Delete Database " + DeleteConfig.attributes['section'].value);
        LoadSearchModal();
    }
};
$('#snackUndo').on('shown.bs.collapse', function () {
    var delayMs = 5000; // delay in milliseconds for Undo to be clicked
    UndoTimeout = setTimeout(function () {
        clearTimeout(UndoTimeout);
        $('#snackUndo').collapse('hide');
        console.log("call SaveDatabaseAPI();")
        SaveDatabaseAPI(DeleteConfig, "Delete");
    }, delayMs);
});

function SaveSelectedDatabase() {
    var CheckedRow = $(DatabaseList).find("tr input[type='radio']:checked");
    if (CheckedRow.length === 0) {  return; }
    var name = CheckedRow.closest('tr').find('td:eq( 2 )')[0].textContent;
    var section = CheckedRow[0].id;
    UpdateSavedLogin(section, name);
};

function CallErrorModal(Message) {
    document.getElementById("errorText").innerText = Message;
    $("#errorModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
}


$('#db-modal').on('hidden.bs.modal', function () {
    $("#DatabaseModal").trigger("reset");
    $('#maincheck').click();
    $('.error-input').removeClass('visible');
    $('.form-control').removeClass('error');
});
$('#search-modal').on('shown.bs.modal', function () {
    $('#searchdatabaselist').val("")
    document.activeElement.blur();
    $('#searchdatabaselist').focus();
});
$("#search-modal").modal({
    backdrop: 'static',
    keyboard: true,
    show: false
});

// toggle connection option type
$(function () {
    $("[name=serverOptions]").click(function () {
        $('.toHide').hide();
        $("#option-" + $(this).val()).show('slow');
        if ($(this).val() === "3") {
            $("#option-1").show('slow');
        }
    });
});

// toggle the user logon fields
$(function () {
    $('#useloginuser').click(function () {
        var useloginuser = $('#useloginuser').is(':checked');
        $('#user, #password, #domain').prop('disabled', useloginuser);
        document.activeElement.blur();
        if (useloginuser === true) {
            $("#user").val(loggedOnUser);
            $("#password").val("");
            $("#domain").val(loggedOnDomain);
            clearError($("#user")[0]);
            clearError($("#password")[0]);
            $("#Login").focus();
        } else {
            if ($("#user").val() === "") { $("#user").focus(); }
            else {  $("#password").focus(); }
        }
    });
});



//this is a log N2 function, really slow.
//https://www.w3schools.com/howto/howto_js_sort_table.asp
function sortTable() {
    var table, rows, switching, i, x, y, shouldSwitch;
    var sortcolumn = 2;
    table = document.getElementById("DatabaseList");
    switching = true;
    while (switching) {
        // Start by saying: no switching is done:
        switching = false;
        rows = table.rows;
        for (i = 0; i < (rows.length - 1); i++) {
            shouldSwitch = false;
            /* Get the two elements you want to compare,
            one from current row and one from the next: */
            x = rows[i].getElementsByTagName("TD")[sortcolumn];
            y = rows[i + 1].getElementsByTagName("TD")[sortcolumn];
            // Check if the two rows should switch place:
//            if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
            if (x.innerText.toLowerCase() > y.innerText.toLowerCase()) {
                shouldSwitch = true;
                break;
            }
        }
        if (shouldSwitch) {
            /* If a switch has been marked, make the switch
            and mark that a switch has been done: */
            rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
            switching = true;
        }
    }
}
