
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Login functions
// https://igniteui.com/help/igdialog-property-reference
// https://github.com/scottoffen/jquery.toaster
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//



function ValidateUserFromCookieValues(bProgramStartup) {
    var username = GetStEncryptedLoginUsernameFromCookie();
    var password = GetStEncryptedLoginPasswordFromCookie();
    AjaxValidateUser(username, password, bProgramStartup, RefreshWithNewLogin, ValidateUserFailed);
}


function OpenLoginDialogFromCookieValues() {
    //var username = GetLoginUsernameFromCookie();
    //var password = GetLoginPasswordFromCookie();
    var username = ThisLoginUsername;
    var password = "";
    OpenLoginDialog(username, password);
}


// Variables for the current logged in user
var ThisLoginUsername = "";
var ThisLoginUserId = "";
var ThisLoginUserAdmin = "";
var ThisLoginUserSuperuser = "";
var ThisLoginUserEmail = "";
var ThisLoginUserWeekStart = "";
var ThisLoginUserLocale = "";
var ThisLoginUserISO4217CurrencyCode = "";
var ThisLoginUserCurrencySym = "";
var PrevLoginUserId = "";


//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Ajax function to validate username/login with server
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
/**
 * Ajax function to validate username/login with server
 * @param {any} username
 * @param {any} password
 * @param {any} onvalidfunction
 * @param {any} oninvalidfunction
 */
function AjaxValidateUser(username, password, bProgramStartup, onvalidfunction, oninvalidfunction) {

    var data = {
        "sUsername": username,
        "sPassword": password,
        "sSaveUserLogin": true,
        "sProgramStartup": bProgramStartup,
    };

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

                // Login success!
                // Check User Rights
                // UR_AUTO_LOGIN, UR_RMBR_PAGES

                // Close all pages when a user logs in (UserSet.UR_RMBR_PAGES)
                if (response.ClosePages)
                    CloseAllContentPanes();

                // Force the user to log in each time (UserSet.UR_AUTO_LOGIN)
                if (response.ForceLogin) {
                    // Force user to log in each time, very onerous but valuable to some users
                    OpenLoginDialog();
                    return;
                }

                ThisLoginUsername = response.Username;
                //ThisLoginPassword = response.Password;
                ThisLoginUserId = response.UserId;
                ThisLoginUserAdmin = response.UserAdmin;
                ThisLoginUserSuperuser = response.UserSuperuser;
                ThisLoginUserEmail = response.UserEmail;
                ThisLoginUserWeekStart = response.UserWeekStart;
                ThisLoginUserLocale = response.Locale;
                ThisLoginUserISO4217CurrencyCode = response.ISO4217CurrencyCode;
                ThisLoginUserCurrencySym = response.CurrencySym;
                ThisSessionTimeoutMinutes = response.SessionTimeoutMinutes;

                if (response.ctoken) {
                    AjaxRestoreSessionLogin(response.ctoken, username, password, onvalidfunction, oninvalidfunction);
                    return;
                }

                // Call RefreshWithNewLogin with the updated user login info
                onvalidfunction(response.Username, response.otoken, response.btoken);
            }
            else {

                // Login failed
                console.log("ValidateUser Failed: " + response.ErrorResults);

                // Check results, then open Login dialog
                if (response.Username && response.Username.length > 0)
                    username = response.Username;
                oninvalidfunction(username, password, response);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("ValidateUser", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}


function AjaxRestoreSessionLogin(ctoken, username, password, onvalidfunction, oninvalidfunction) {

    var data = {
        "ctoken": ctoken,
        "sUsername": username,
        "sPassword": password,
    };

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

                if (!response.Username) {
                    OpenLoginDialog();
                    return;
                }

                // Call RefreshWithNewLogin to signal a good login
                onvalidfunction(response.Username);
                //ToastMessage("AjaxRestoreSessionLogin GOOD: " + ThisLoginUserAdmin);
            }
            else {

                // Login failed
                console.log("AjaxRestoreSessionLogin Failed: " + response.ErrorResults);

                // Check results, then open Login dialog
                if (response.Username && response.Username.length > 0)
                    username = response.Username;
                oninvalidfunction(username, password, response);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxRestoreSessionLogin", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}




/**
 * Failed to validate username/password
 * Prompt user for resolution
 * Most likely, a bad username
 * @param {any} username
 * @param {any} password
 * @param {any} response
 */
function ValidateUserFailed(username, password, response) {

    console.log("ValidateUserFailed: " + response.HasDatabaseConnection + ", Error: " + response.ErrorResults)

    // Has a database connection?
    if (!response.HasDatabaseConnection) {

        // No database connection
        PopupMessageBox("Database Connection Failed", response.ErrorResults);
        return;
    }

    // Open login dialog to collect username and password
    password = "";
    OpenLoginDialog(username, password);
}



//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Open the login dialog
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
var bLoginDialogIsOpen = false;
function OpenLoginDialog(username, password) {

    // Open the user login dialog for username and password
    // See: LoginDialogView.cshtml

    // Set the current values
    $("#igDialogLogonUsernameTextBox").val(username);
    $("#igDialogLogonPasswordTextBox").val(password);
    $("#igDialogLogonUsernameTextBox").select();
    $("#igDialogLoginCancelButton").show();

    var nDlgWidth = 400;
    var nDlgHeight = 300;
    var nWindowWidth = $(window).width();
    var nWindowHeight = $(window).height();
    if (nWindowWidth < nDlgWidth)
        nDlgWidth = nWindowWidth * 0.98;
    if (nWindowHeight < nDlgHeight)
        nDlgHeight = nWindowHeight * 0.95;

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

    //ResizeDialogToWindowSize("igDialogLogon");
    CenterDialog("igDialogLogon");


    // Set up controls
    AjaxFillImage($("#igDialogLogonUserImage"), "stdata.images.enabled.people-man-5-filled-key-filled@256px.png", 256);
    $("#igDialogLogonUsernameTextBox")[0].focus();
    $("#igDialogLogonUsernameTextBox").focus();
    FocusAndSelectAllOnTimeout("igDialogLogonUsernameTextBox");
    bLoginDialogIsOpen = true;

    // OK button click
    $("#igDialogLoginOKButton").unbind().click(function () {
        AjaxValidateUser($("#igDialogLogonUsernameTextBox").val(), $("#igDialogLogonPasswordTextBox").val(), false/*bProgramStartup*/, RefreshWithNewLogin, DisplayBadLogin);
    });

    // Cancel button click
    $("#igDialogLoginCancelButton").unbind().click(function () {
        CloseLoginDialog();
    });

    // Enter key closes dialog
    $('#igDialogLogonUsernameTextBox').unbind().keypress(function (e) {
        var key = e.which;
        if (key == 13)  // the enter key code
        {
            $('#igDialogLoginOKButton').click();
            return false;
        }
    });

    $('#igDialogLogonPasswordTextBox').unbind().keypress(function (e) {
        var key = e.which;
        if (key == 13)  // the enter key code
        {
            $('#igDialogLoginOKButton').click();
            return false;
        }
    });
}


//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Close the login dialog
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
function CloseLoginDialog() {
    $("#igDialogLogon").igDialog("close");
    bLoginDialogIsOpen = false;
}

function IsLoginDialogOpen() {
    return bLoginDialogIsOpen;
}



//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// A bad username/password was entered
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
function DisplayBadLogin(BadUsername, BadPassword, response) {

    // Tell user that the username was no good
    ToastError("Invalid Login", response.ErrorResults);
}







//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Change password
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
var bChangePasswordDialogIsOpen = false;
var DatabaseConnectionResults = {};
function OnChangeUserPassword() {

    var nDlgWidth = 400;
    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
    $("#igDialogChangePassword").igDialog({ modal: true, headerText: "Change Password", width: nDlgWidth, height: nDlgHeight, resizable: false, closeOnEscape: true, openAnimation: "", closeAnimation: "fade"/*, openAnimation: "fade"*/ });
    $("#igDialogChangePassword").igDialog("open");

    // Set up controls
    bChangePasswordDialogIsOpen = true;

    // Dialog controls
    $("#igDialogChangePasswordNameLabel").html(ThisLoginUsername);
    $("#igDialogChangePasswordOKButton").unbind().click(function () { OnChangePasswordDialogOk(); });

    // Cancel button click
    $("#igDialogChangePasswordCancelButton").unbind().click(function () { CloseChangePasswordDialog(); });

    // Set focus
    FocusAndSelectAllOnTimeout("igDialogChangePasswordOldTextBox");
}

function OnChangePasswordDialogOk() {

    var OldPassword = $("#igDialogChangePasswordOldTextBox").val();
    var NewPassword = $("#igDialogChangePasswordNewTextBox").val();
    var ConfirmPassword = $("#igDialogChangePasswordConfirmTextBox").val();

    // Do the passwords match?
    if (NewPassword !== ConfirmPassword) {
        ToastError("The passwords don't match.");
        return;
    }

    // Empty passwords?
    if (!NewPassword) {

    }

    CloseChangePasswordDialog();

    // Call the server to change the password
    AjaxChangeUserPassword(ThisLoginUserId, OldPassword, NewPassword);
}


function CloseChangePasswordDialog() {
    $("#igDialogChangePassword").igDialog("close");
    bChangePasswordDialogIsOpen = false;
}


function AjaxChangeUserPassword(UserId, OldPassword, NewPassword) {

    var params = {
        "UserId": UserId,
        "OldPassword": OldPassword,
        "NewPassword": NewPassword,
    };

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

                // Double-check results
                //if (response.SetPassword === response.ResultPassword) {
                if (response.btoken === response.rtoken) {
                    // Save the password
                    SetStEncryptedLoginPasswordCookie(response.btoken);
                    ToastMessage("Your password has been set!");
                }
            }
            else {
                ToastError("Change Password", response.ErrorResults);
                PopupErrorMessage("Change Password", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxApplySettings", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}



//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// A good username/password was entered
// Refresh the entire page based on the new login
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
function RefreshWithNewLogin(NewUsername, StEncryptedUsername, StEncryptedPassword) {

    if (!NewUsername )
        return;

    // Save the new username and password to cookies
    if (StEncryptedUsername) {
        SetStEncryptedLoginUsernameCookie(StEncryptedUsername);
        SetStEncryptedLoginPasswordCookie(StEncryptedPassword);
    } else {
        SetStEncryptedLoginUsernameCookie("");
        SetStEncryptedLoginPasswordCookie("");
    }

    // Clear values used for Ajax for displaying the selected object
    ClearSelectedObjectHiddenValues();

    // Tell user that the login was good
    if (ThisLoginUserId != PrevLoginUserId) {

        // Different user?  (Was logged in, but entered a new username)
        if (PrevLoginUserId && PrevLoginUserId.length > 0) {
            // This user was logged in, but then logged in again with a new name
            // Because the user changed, all the UI must change for that person's rights
            // This is like restarting the Windows app because each user has view rights to see different things in the app
            window.location.reload();
            return;
        }
        else {
            // Normal login
            // The browser was launched and the user logged in for the first time
            // Tell them the login was successful
            ToastMessage("Login", NewUsername);
        }
    }

    // Set the text of the "Login" button(s)
    // User: Ray
    $("#LoginUserButton").html("User: " + NewUsername);
    $("#FileLoginUserButton").html("User: " + NewUsername);

    // Close login dialog, in case it is still open
    if (IsLoginDialogOpen())
        CloseLoginDialog();

    // Show or hide ribbon items based on logged-in user rights
    ShowRibbonElementsByAccessRights();

    // Load all the views from cookie
    ShowDockManager();
    LoadDockManagerLayoutFromCookie();
    LoadFilterPanelPinnedFromCookie();
    LoadPropertiesPanelPinnedFromCookie();
    LoadSettingsPanelPinnedFromCookie();
    LoadSplitterPaneSizesFromCookie();
    LoadAutoRefreshValuesFromCookies();
    CreateAutoRefreshTimer();
    ResetSessionTimeoutTimer();

    if (!bSmallSizeApp) {
        // Refresh all the views with the new login
        // Each login has different rights and data visibility
        AjaxRefreshFilterTreeView($("#"+FilterTreePartialViewDivId));
        RefreshPropertyGridViewFromHiddenSelection($("#"+PropertyGridPartialViewDivId));
    }

    // Remember this for the next login
    PrevLoginUserId = ThisLoginUserId;

    // Check licensing at startup
    CheckLicensingAtStartup();

    // Send emails and perform period updates
    StartOnIdle();
}



function OnLogout() {

    PopupYesNoWithCallback("Logout", "Are you sure want to log out?", AjaxLogout);

    //AjaxLogout();
}



function AjaxLogout() {

    var params = {
    };

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

                // Successful logout
                // Clear the cookies
                SetStEncryptedLoginUsernameCookie("");
                SetStEncryptedLoginPasswordCookie("");

                // Close all the tabs because they won't work without a login
                // If the user clicks Cancel, the tabs won't work
                // And, the new login may have different user rights, so the tabs will be irrelevant
                CloseAllContentPanes();

                // Clear the username and password text
                $("#igDialogLogonUsernameTextBox").val("");
                $("#igDialogLogonPasswordTextBox").val("");
                $("#igDialogLogonUsernameTextBox")[0].focus();
                $("#igDialogLogonUsernameTextBox").focus();

                // Hide Cancel button so they can't close this dialog
                $("#igDialogLoginCancelButton").hide();
            }
            else {
                ToastError("Logout", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText + "\r\nText: " + BarcodeText;
            ToastError("v", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}
