
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Licensing functions
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//


function CheckLicensingAtStartup() {

    AjaxCheckUserLicenses(0/*NumChecks*/);
}



function AjaxCheckUserLicenses(NumChecks) {

    var params = {
        "NumChecks": NumChecks
    };

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

                // Limit the number of checks, then shut down the app
                NumChecks++;
                if (NumChecks > 2) {

                    // TODO: P9 Store shutdown in a cookie, then limit NumChecks to 1

                    ShutdownApp(response.LicenseMessage);
                    return;
                }

                // Sufficient licenses?
                if (response.Licensed) {

                    // Licensed (for now)
                    // Check back tomorrow at this time
                    // Why? Because a user account can be altered or shut off (new user-seats added or removed)
                    setTimeout(function () { AjaxCheckUserLicenses(0/*NumChecks*/); }, (1000 * 60 * 60 * 24)/*one day*/);
                    return;

                    // Nothing more to do!
                }
                else {

                    // Not licensed!
                    // Generic error if there is none
                    if (!response.LicenseMessage)
                        response.LicenseMessage = "Please check your user licenses! (Verify active users verses licenses)";

                    // Inform user that licenses are insufficient
                    ShowUsersGridView();
                    ActivateDocumentTabByContentType("USERSGRID");
                    PopupMessageBox(APP_NAME + " Licenses", response.LicenseMessage);

                    // Give a few minutes to figure this out, then hit them again and again
                    setTimeout(function () { AjaxCheckUserLicenses(NumChecks); }, (1000 * 60 * 2)/*two minutes*/);

                    // A lasting message to help understand the issue
                    ToastErrorWithTimeout("Licenses", response.LicenseMessage, 60000);
                }
            }
            else {
                ToastError("AjaxCheckUserLicenses", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxCheckUserLicenses", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });

}


