
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Validate database functions
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//

// Results of "GetDatabaseConnectionStatus"
var DbConnected = false;
var DbConnectionResults = "";
var DbDatabaseName = "";
var DbDatabaseType = "";
var DbDatabaseFileDsnPath = "";
var DbDatabaseFileDsnName = "";
var ExeVersion = 0.00;
var DbVersion = 0.00;





//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Get database connection status, and perform database upgrade if necessary
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
/**
 * Get database connection status
 * Validate the database if necessary
 * Example: Upgrade database from 25.02 to 25.03 by adding new tables and columns
 */
function AjaxCheckDatabaseConnectionAndValidation() {

    OpenCheckingDatabaseConnectionDialog();

    var data = {
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxGetDatabaseConnectionStatus",
        type: "POST",
        data: JSON.stringify(data),
        dataType: "json",
        contentType: "application/json",
        success: function (response) {

            DatabaseConnectionResults = response;
            CloseCheckingDatabaseConnectionDialog();

            if (response.Success) {
                if (response.Connected) {

                    // Use VarinfoSet to override favicon
                    // See "Varinfo" database record, for resellers and product overloads
                    // Use the 32x32 logo that is loaded into a Varinfo.ImageObject32 record
                    // Varinfo.ImagePath32 can be used to load a file from disk and place the data into Varinfo.ImageObject32
                    if (response.VarinfoLogoImage32DataUri) {
                        SetFaviconFromDataUri(response.VarinfoLogoImage32DataUri);
                    }

                    // Connected to database
                    var DatabaseStatus = Decrypt146(response.ThemeExt) + ", " + Decrypt146(response.ThemeBase);
                    $("#FileDatabaseButton").html(DatabaseStatus);

                    DbConnected = response.Connected;
                    DbConnectionResults = response.ConnectionResults;
                    DbDatabaseName = Decrypt146(response.ThemeBase);
                    DbDatabaseType = Decrypt146(response.ThemeExt);
                    DbDatabaseFileDsnPath = Decrypt146(response.ThemePath);
                    DbDatabaseFileDsnName = Decrypt146(response.ThemeName);
                    ExeVersion = response.ExeVersion;
                    DbVersion = response.ThemeVersion;

                    // Does the database need to be upgraded?
                    if (response.ThemeVersion < response.ExeVersion) {
                        // Database is old or empty
                        // Upgrade the database to the latest version
                        OpenValidateDatabaseDialog();
                    }
                    else {
                        // Database is compatible with this version of the program
                        // Proceed with login
                        ValidateUserFromCookieValues(true/*bProgramStartup*/);
                    }
                }
                else {
                    // Connection failed!
                    // Not connected to database
                    PopupErrorMessage("Database Connection Failed", response.ConnectionResults);

                    // Shut down the app
                    ShutdownApp("Database Connection Failed\r\n\r\n" + response.ConnectionResults);
                }
            }
            else {
                // Not successful
                ToastError("AjaxCheckDatabaseConnectionAndValidation", "Success FALSE\r\n\r\n" + response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {

            CloseCheckingDatabaseConnectionDialog();

            var errormsg = "Ajax Function Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxCheckDatabaseConnectionAndValidation", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}




//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Open the Validate Database dialog
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
var bValidateDatabaseDialogIsOpen = false;
var DatabaseConnectionResults = {};
function OpenValidateDatabaseDialog() {

    var nDlgWidth = 550;
    var nDlgHeight = 380;
    var nWindowWidth = $(window).width();
    var nWindowHeight = $(window).height();
    if (nWindowWidth < nDlgWidth)
        nDlgWidth = nWindowWidth * 0.95;
    if (nWindowHeight < nDlgHeight)
        nDlgHeight = nWindowHeight * 0.95;

    // Open the dialog
    // igniteui.com/help/igdialog-property-reference
    $("#igDialogValidateDatabase").igDialog({ modal: true, headerText: "Validate Database", width: nDlgWidth, height: nDlgHeight, resizable: false, closeOnEscape: true, openAnimation: "", closeAnimation: "fade"/*, openAnimation: "fade"*/ });
    $("#igDialogValidateDatabase").igDialog("open");

    // Set up controls
    bValidateDatabaseDialogIsOpen = true;

    // Dialog controls
    $("#igDialogValidateDatabaseProgramVersion").html(DatabaseConnectionResults.ExeVersion);
    $("#igDialogValidateDatabaseDbVersion").html(DatabaseConnectionResults.ThemeVersion);
    $("#igDialogValidateDatabaseCredentialsPath").html(Decrypt146(DatabaseConnectionResults.ThemePath));

    // Cancel button click
    $("#igDialogValidateDatabaseCancelButton").unbind().click(function () { bCancelValidateDatabase = true; CloseValidateDatabaseDialog(); });

    // Use Ajax to upgrade database
    bCancelValidateDatabase = false;
    AjaxNextValidateDatabaseColumn(true/*bRestartValidation*/);
}



var bCancelValidateDatabase = false;
/**
 * Validate the next database column
 * This may involve altering the database with new tables or columns
 * @param {any} bRestartValidation
 */
function AjaxNextValidateDatabaseColumn(bRestartValidation) {

    var data = {
        RestartValidation: bRestartValidation,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxNextValidateDatabaseColumn",
        type: "POST",
        data: JSON.stringify(data),
        dataType: "json",
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {

                // Update progress
                var nProgressValue = response.ProgressValue;
                if (!nProgressValue)
                    nProgressValue = 0;
                $('#igDialogValidateDatabaseProgressBar').val(nProgressValue);
                $("#igDialogValidateDatabaseDetailsLabel").html(response.ProgressDetails);

                // Done?
                if (response.Complete || bCancelValidateDatabase) {

                    // Close this validation dialog
                    CloseValidateDatabaseDialog();

                    // Database is compatible with this version of the program
                    // Proceed with login
                    ValidateUserFromCookieValues(true/*bProgramStartup*/);
                }
                else {
                    // Next column
                    //AjaxNextValidateDatabaseColumn(false/*bRestartValidation*/);

                    // Avoid recursive stack overflow
                    setTimeout(function() { AjaxNextValidateDatabaseColumn(false/*bRestartValidation*/); }, 150);
                }
            }
            else {
                ToastError("AjaxNextValidateDatabaseColumn", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxNextValidateDatabaseColumn", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}




function AjaxPopupDatabaseConnectionStatus() {

    var data = {
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxGetDatabaseConnectionStatus",
        type: "POST",
        data: JSON.stringify(data),
        dataType: "json",
        contentType: "application/json",
        success: function (response) {

            if (response.Success) {

                //Connected = DatabaseConnection.bConnectionSuccess,
                //ConnectionResults = sCheckConnectionResults,
                //DatabaseName = DatabaseConnection.GetDatabaseName(),
                //DatabaseType = DatabaseConnection.GetDatabaseType(),
                //DatabaseFileDsnPath = DatabaseConnection.sFileDsnPathname,
                //DatabaseFileDsnName = System.IO.Path.GetFileName(DatabaseConnection.sFileDsnPathname),
                //ExeVersion = DatabaseConnection.dExeVersion,
                //DbVersion = DatabaseConnection.dDbVersion,

                DbConnected = response.Connected;
                DbConnectionResults = response.ConnectionResults;
                DbDatabaseName = Decrypt146(response.ThemeBase);
                DbDatabaseType = Decrypt146(response.ThemeExt);
                DbDatabaseFileDsnPath = Decrypt146(response.ThemePath);
                DbDatabaseFileDsnName = Decrypt146(response.ThemeName);
                ExeVersion = response.ExeVersion;
                DbVersion = response.ThemeVersion;

                var sMsg = "";
                sMsg += "Credentials file: " + Decrypt146(response.ThemePath) + "\r\n\r\n";
                sMsg += "Database name: " + Decrypt146(response.ThemeBase) + "\r\n";
                sMsg += "Database type: " + Decrypt146(response.ThemeExt) + "\r\n";
                sMsg += "Database version: " + response.ThemeVersion + "\r\n\r\n";
                sMsg += "Status: " + response.ConnectionResults + "\r\n";
                PopupInfoMessage("Database Connection", sMsg);
            }
            else {
                // Not successful
                ToastError("GetDatabaseConnectionStatus", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxPopupDatabaseConnectionStatus", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}




//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Open the Checking Database Connection dialog
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
var bCheckingDatabaseConnectionDialogIsOpen = false;
function OpenCheckingDatabaseConnectionDialog() {

    // Open the dialog
    // igniteui.com/help/igdialog-property-reference
    $("#igDialogCheckingDatabaseConnection").igDialog({ modal: false, headerText: "Checking Database Connection", height: 180, width: 350, resizable: false, showCloseButton: false, closeOnEscape: true, openAnimation: "", closeAnimation: "fade"/*, openAnimation: "fade"*/ });
    $("#igDialogCheckingDatabaseConnection").igDialog("open");

    // Set up controls
    bCheckingDatabaseConnectionDialogIsOpen = true;
}


//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Close the dialog
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
function CloseValidateDatabaseDialog() {
    $("#igDialogValidateDatabase").igDialog("close");
    bValidateDatabaseDialogIsOpen = false;
}

function IsValidateDatabaseDialogOpen() {
    return bValidateDatabaseDialogIsOpen;
}



function CloseCheckingDatabaseConnectionDialog() {
    $("#igDialogCheckingDatabaseConnection").igDialog("close");
    bCheckingDatabaseConnectionDialogIsOpen = false;
}

function IsCheckingDatabaseConnectionDialogOpen() {
    return bCheckingDatabaseConnectionDialogIsOpen;
}

