$(document).ready(function () {
    var licensesByKey;
    var verifiedLicenses;
    var licensesAdded;
    var licenseAddFailures;
    var allSelectedLicenses = new Array();
    var selectedLeasedLicenses = new Array();
    var allSelectedLicensesByKey = new Object();
    var licensesLeftToRemove = 0;
    var licensesLeftToRelease = 0;

    function getLicenseStatusString(statusOrdinal) {
        switch (statusOrdinal) {
            case 0:
                return "OK";
            case 1:
                return "NearExpiry";
            case 2:
                return "Expired";
            case 3:
                return "Failure";
        }
    }

    $("#ShowAddLicensesButton").click(function () {
        $("#LicenseName").val("");
        $("#Licenses").val("");
        $("#GotoStep2").addClass("Disabled");

        $("#PopupOverlay").css("height", $(document).height() - 130);
        $("#PopupOverlay").show();
        $("#Step1").show();
        $("#Step2").hide();

        $("#LicenseName").focus();
    });

    $("#Licenses").on('change keyup paste', function () {
        if ($("#Licenses").val().length == 0) {
            $("#GotoStep2").addClass("Disabled");
        } else {
            $("#GotoStep2").removeClass("Disabled");
        }
    });

    $("#RemoveLicensesButton").click(function () {
        licensesLeftToRemove = allSelectedLicenses.length;
        for (var i = 0; i < allSelectedLicenses.length; i++) {
            LicenseManagementController.RemoveLicense(allSelectedLicenses[i].LicenseName, allSelectedLicenses[i].LicenseKey, onLicenseRemoved);
        }
    });

    $("#ReleaseLicensesButton").click(function () {
        licensesLeftToRelease = selectedLeasedLicenses.length;
        for (var i = 0; i < selectedLeasedLicenses.length; i++) {
            LicenseManagementController.ReleaseLicense(selectedLeasedLicenses[i].LicenseName, selectedLeasedLicenses[i].LicenseKey, onLicenseReleased);
        }
    });

    function onLicenseRemoved(ajaxResult) {
        licensesLeftToRemove--;

        if (licensesLeftToRemove == 0) {
            clearSelection();
            refreshLicenses();
        }
    }

    function onLicenseReleased(ajaxResult) {
        licensesLeftToRelease--;

        if (licensesLeftToRelease == 0) {
            clearSelection();
            refreshLicenses();
        }
    }

    $(".CancelAddLicensesButton").click(function () {
        $("#PopupOverlay").hide();
    });

    $("#GotoStep2").click(function () {
        if ($(this).hasClass("Disabled"))
            return;

        verifyLicenses($("#LicenseName").val(), $("#Licenses").val());

        $("#Step1").hide();
        $("#Step2").show();
    });

    $("#BackToStep1").click(function() {
        $("#Step1").show();
        $("#Step2").hide();
    });

    $("#PopupOverlay").click(function (e) {
        if (e.target.id == "PopupOverlay")
            $("#PopupOverlay").hide();
    });

    $("#FinishAddLicenses").click(function () {
        licenseAddFailures = new Array();
        licensesAdded = 0;

        for (var i = 0; i < verifiedLicenses.length; i++) {
            LicenseManagementController.AddLicense(verifiedLicenses[i].LicenseName, verifiedLicenses[i].LicenseKey, addLicenseCompleted);
        }
    });

    function clearSelection() {
        allSelectedLicenses = new Array();
        selectedLeasedLicenses = new Array();
        allSelectedLicensesByKey = new Object();
    }

    function addLicenseCompleted(ajaxResult) {
        if (ajaxResult.IsSuccess)
            licensesAdded++;
        else {
            licenseAddFailures.push(ajaxResult.Message);
        }

        if ((licensesAdded + licenseAddFailures.length) >= verifiedLicenses.length) {
            $("#PopupOverlay").hide();
            refreshLicenses();
        }
    }

    function constructLicenseTable(managedLicenses) {
        var table = $("#LicenseListTable");
        table.empty();

        licensesByKey = new Object();

        if (managedLicenses.length == 0) {
            $("#NoLicensesMessage").show();
            table.hide();
            return;
        }
        
        $("#NoLicensesMessage").hide();
        table.show();

        table.append("<tr class='HeaderRow'><td><input type='checkbox' id='SelectAllCheckbox'></td><td>Licensed Name</td><td>Key</td><td>Issued</td><td>Expires</td><td>Free Upgrades Until</td><td>Leased To</td><td>Lease Expires</td></tr>");

        for (var i = 0; i < managedLicenses.length; i++) {
            var selectionState = allSelectedLicensesByKey[managedLicenses[i].LicenseKey] == null ? "" : " checked='true'";

            var row = "<tr class='ContentRow " + getLicenseStatusString(managedLicenses[i].Status) + "'><td><input type='checkbox' class='LicenseSelectionCheckbox' id='" + managedLicenses[i].LicenseKey + "'" + selectionState + ">"
                + "</td><td class='Clickable'>" + managedLicenses[i].LicenseName
                + "</td><td class='Clickable KeyField'>" + managedLicenses[i].LicenseKey
                + "</td><td class='Clickable'>" + ToJavascriptDate(managedLicenses[i].IssueDate).format(defaultDateFormat)
                + "</td><td class='Clickable ExpiryDateField'>" + formatExpiryDate(managedLicenses[i].ExpiryDate)
                + "</td><td class='Clickable'>" + formatExpiryDate(managedLicenses[i].MaintenanceExpiry);

            if (managedLicenses[i].Lease == null) {
                row = row
                    + "</td><td>-"
                    + "</td><td>"
                    + "</td></tr>";
            } else {
                row = row
                    + "</td><td class='Clickable LeaseField'>" + managedLicenses[i].Lease.ServerUserName
                    + "</td><td class='Clickable'>" + ToJavascriptDate(managedLicenses[i].Lease.LeaseEndDate)
                    + "</td></tr>";
            }

            table.append(row);
            licensesByKey[managedLicenses[i].LicenseKey] = managedLicenses[i];
        }

        $("#SelectAllCheckbox").click(function () {
            var isChecked = $("#SelectAllCheckbox").prop("checked");
            $(".LicenseSelectionCheckbox").prop("checked", isChecked);
            refreshSelectionState();
        });

        $("#LicenseListTable td.Clickable").click(function () {
            var checkbox = $(this).parent().find(".LicenseSelectionCheckbox");
            var isChecked = checkbox.prop("checked");
            checkbox.prop("checked", !isChecked);
            refreshSelectionState();
        });

        $(".LicenseSelectionCheckbox").click(function () {
            refreshSelectionState();
        });

        refreshSelectionState();
    }

    function refreshSelectionState() {
        allSelectedLicenses = new Array();
        selectedLeasedLicenses = new Array();
        allSelectedLicensesByKey = new Object();

        $(".LicenseSelectionCheckbox").each(function () {
            var row = $(this).parent().parent();

            if ($(this).prop("checked")) {
                var managedLicense = licensesByKey[$(this).prop("id")];
                allSelectedLicenses.push(managedLicense);
                allSelectedLicensesByKey[managedLicense.LicenseKey] = managedLicense;

                if (managedLicense.Lease != null)
                    selectedLeasedLicenses.push(managedLicense);

                row.addClass("Selected");
            } else {
                row.removeClass("Selected");
            }
        });

        if (allSelectedLicenses.length == 0)
            $("#RemoveLicensesButton").addClass("Disabled");
        else
            $("#RemoveLicensesButton").removeClass("Disabled");


        if (selectedLeasedLicenses.length == 0)
            $("#ReleaseLicensesButton").addClass("Disabled");
        else
            $("#ReleaseLicensesButton").removeClass("Disabled");
    }

    function verifyLicenses(licenseName, keys) {
        LicenseManagementController.VerifyLicenses(licenseName, keys, constructLicenseVerificationTable);
    }

    function constructLicenseVerificationTable(verifyResults) {
        var table = $("#LicenseVerificationTable");
        var successCount = 0;
        var failureCount = 0;

        verifiedLicenses = new Array();

        table.empty();

        table.append("<tr class='HeaderRow'><td>Licensed Name</td><td>Key</td><td>Issued</td><td>Expires</td><td>Details</td></tr>");

        for (var i = 0; i < verifyResults.length; i++) {
            table.append("<tr class='ContentRow " + (verifyResults[i].Message == null? "OK" : "Failure") + "'><td>" + verifyResults[i].License.LicenseName
                + "</td><td class='KeyField'>" + verifyResults[i].License.LicenseKey
                + "</td><td>" + ToJavascriptDate(verifyResults[i].License.IssueDate).format(defaultDateFormat)
                + "</td><td>" + formatExpiryDate(verifyResults[i].License.ExpiryDate)
                + "</td><td class='LicenseDetailsField'>" + (verifyResults[i].Message == null ? "OK" : verifyResults[i].Message)
                + "</td></tr>");

            if (verifyResults[i].IsValid) {
                successCount++;
                verifiedLicenses.push(verifyResults[i].License);
            } else
                failureCount++;
        }

        if (successCount > 0 && failureCount > 0) {
            $("#SomeLicensesOKSummary").show();
            $("#AllLicensesOKSummary").hide();
            $("#NoLicensesOKSummary").hide();
        } else if (successCount > 0) {
            $("#SomeLicensesOKSummary").hide();
            $("#AllLicensesOKSummary").show();
            $("#NoLicensesOKSummary").hide();
        } else {
            $("#SomeLicensesOKSummary").hide();
            $("#AllLicensesOKSummary").hide();
            $("#NoLicensesOKSummary").show();
        }
    }

    function refreshLicenses() {
        LicenseManagementController.GetLicenses(function(getLicensesResult) {
            constructLicenseTable(getLicensesResult.Licenses);
        });
    }

    function formatExpiryDate(jsonDate) {
        if (jsonDate == "/Date(253402253999999)/")
            return "(never)";

        return ToJavascriptDate(jsonDate).format(defaultDateFormat);
    }

    refreshLicenses();
    refreshSelectionState();
})