var AjaxMethod;
(function (AjaxMethod) {
    AjaxMethod["POST"] = "POST";
    AjaxMethod["GET"] = "GET";
})(AjaxMethod || (AjaxMethod = {}));
var AjaxOptions = (function () {
    function AjaxOptions(fileds) {
        if (fileds) {
            Object.assign(this, fileds);
        }
    }
    return AjaxOptions;
}());
var AjaxService = (function () {
    function AjaxService() {
    }
    AjaxService.prototype.send = function (options) {
        var that = this;
        var call = $.ajax({
            url: options.url,
            type: options.method,
            data: options.data,
            success: function (d) {
                if (options.callback) {
                    options.callback(d);
                }
                if (options.successMsg) {
                    DevExpress.ui.notify(options.successMsg, "success", 5000);
                }
            },
            error: function (d) {
                if (options.errorCallback) {
                    options.errorCallback(d);
                }
                if (options.errorMsg) {
                    DevExpress.ui.notify(options.errorMsg, "error", 5000);
                }
            }
        });
        return call;
    };
    return AjaxService;
}());

var CopyService = (function () {
    function CopyService(navigator, document) {
        this.container = null;
        this.tryToCopyInterval = null;
        this.navigator = navigator;
        this.document = document;
    }
    CopyService.prototype.Copy = function (callback) {
        var that = this;
        this.tryToCopyInterval = setInterval(function () {
            var copied = that.TryCopy();
            if (copied) {
                clearInterval(that.tryToCopyInterval);
                if (typeof callback !== 'undefined') {
                    callback(true);
                }
            }
        }, 5);
    };
    CopyService.prototype.TryCopy = function () {
        this.container.focus();
        this.container.select();
        return this.document.execCommand("copy");
    };
    CopyService.prototype.Create = function (toCopy) {
        this.Finalize();
        this.container = this.document.createElement("textarea");
        this.container.style.position = "absolute";
        this.container.style.opacity = '0';
        this.container.style.left = "-9999px";
        this.container.style.top = "0";
        this.container.style.width = "0px";
        this.container.style.height = "0px";
        this.container.textContent = toCopy;
        this.document.body.appendChild(this.container);
    };
    CopyService.prototype.Finalize = function () {
        if (this.container !== null) {
            this.document.body.removeChild(this.container);
            this.container = null;
        }
        if (this.tryToCopyInterval !== null) {
            clearInterval(this.tryToCopyInterval);
        }
    };
    return CopyService;
}());

var BaseView = (function () {
    function BaseView() {
        this.BindLayoutMenu();
        this.LogDbCallsErrors();
    }
    BaseView.prototype.BindLayoutMenu = function () {
        if (document.location.href.indexOf('Scheduler') <= -1 && (document.location.href.indexOf('Reports') > -1 || document.location.href.indexOf('Visualize') > -1)) {
            $('#reportsMenuDx').addClass('active');
            $('#usersMenuDx').removeClass('active');
            $('#logsMenuDx').removeClass('active');
            if (this.IsDefined($('#scheduleMenuDx'))) {
                $('#scheduleMenuDx').removeClass('active');
            }
        }
        else if (document.location.href.indexOf('Management') > -1 ||
            document.location.href.indexOf('ConnectionProfiles') > -1 ||
            document.location.href.indexOf('Settings') > -1) {
            $('#reportsMenuDx').removeClass('active');
            $('#usersMenuDx').addClass('active');
            $('#logsMenuDx').removeClass('active');
            if (this.IsDefined($('#scheduleMenuDx'))) {
                $('#scheduleMenuDx').removeClass('active');
            }
        }
        else if (document.location.href.indexOf('Logs') > -1) {
            $('#reportsMenuDx').removeClass('active');
            $('#usersMenuDx').removeClass('active');
            $('#logsMenuDx').addClass('active');
            if (this.IsDefined($('#scheduleMenuDx'))) {
                $('#scheduleMenuDx').removeClass('active');
            }
        }
        else if (document.location.href.indexOf('Scheduler') > -1) {
            $('#reportsMenuDx').removeClass('active');
            $('#usersMenuDx').removeClass('active');
            $('#logsMenuDx').removeClass('active');
            if (this.IsDefined($('#scheduleMenuDx'))) {
                $('#scheduleMenuDx').addClass('active');
            }
        }
        $('#reportsMenuDx').on("click", function (e) {
            document.location.href = "/Reports/Index";
        });
        $('#usersMenuDx').on("click", function (e) {
            document.location.href = "/Management/Index";
        });
        $('#logsMenuDx').on("click", function (e) {
            document.location.href = "/Logs/Index";
        });
        if (this.IsDefined($('#scheduleMenuDx'))) {
            $('#scheduleMenuDx').on("click", function (e) {
                document.location.href = "/Reports/Scheduler";
            });
        }
    };
    BaseView.prototype.IsNotEmpty = function (obj) {
        return this.IsDefined(obj) && obj !== "" && obj !== " ";
    };
    BaseView.prototype.IsDefined = function (obj) {
        return typeof obj !== 'undefined' && obj !== null;
    };
    BaseView.prototype.LogDbCallsErrors = function () {
        var that = this;
        DevExpress.data.setErrorHandler(function (error) {
            that.StatusCheck().done(function () {
                DevExpress.ui.notify("Error occured: " + error.message, "error", 5500);
            });
        });
    };
    BaseView.prototype.StatusCheck = function () {
        return $.ajax({
            url: '/Visualize/StatusCheck',
            type: "GET",
            statusCode: {
                401: function () {
                    window.location.reload();
                }
            }
        });
    };
    BaseView.prototype.LogError = function (msg, time, height) {
        DevExpress.ui.notify({ message: msg, height: height }, "error", time != null ? time : 5500);
    };
    BaseView.prototype.Info = function (msg, time, height) {
        DevExpress.ui.notify({ message: msg, height: height }, "info", this.IsDefined(time) ? time : 5500);
    };
    BaseView.prototype.Loading = function (text) {
        var loadingPanel = $('#wrLoadingPanel').dxLoadPanel("instance");
        return loadingPanel;
    };
    BaseView.prototype.IsMobile = function () {
        var currentWidth = $(window).width();
        return currentWidth < 992;
    };
    return BaseView;
}());
document.addEventListener("DOMContentLoaded", function documentReady() {
    this.removeEventListener("DOMContentLoaded", documentReady);
    var view = new BaseView();
});

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var APIKeysView = (function (_super) {
    __extends(APIKeysView, _super);
    function APIKeysView() {
        var _this = _super.call(this) || this;
        _this.callController = "/Settings";
        _this.apiGridSelectedIndex = -1;
        _this.ajaxService = new AjaxService();
        _this.copyService = new CopyService(navigator, document);
        return _this;
    }
    APIKeysView.prototype.CopyAPIKey = function (e) {
        this.copyService.Create($("#Key").val().toString());
        this.copyService.Copy(function () {
            DevExpress.ui.notify('API Key Copied!', "info", 5000);
        });
        console.log($("#Key").val().toString());
    };
    APIKeysView.prototype.DeleteAPIKey = function (e) {
        var that = this;
        if (this.apiGridSelectedIndex >= 0) {
            var result = DevExpress.ui.dialog.confirm("Are you you want to delete this API Key?", "Delete");
            result.done(function (dialogResult) {
                if (dialogResult) {
                    var callUrl = that.callController + '/DeleteAPIKey';
                    var data = {
                        __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
                        key: $("#apiGridDx").dxDataGrid("instance").getSelectedRowsData()[0].Id
                    };
                    var callOptions = new AjaxOptions({
                        url: callUrl,
                        method: AjaxMethod.POST,
                        data: data,
                        callback: function (response) {
                            that.apiGridSelectedIndex = -1;
                            $("#apiGridDx").dxDataGrid("instance").deselectAll();
                            $("#apiGridDx").dxDataGrid("instance").refresh();
                        },
                        errorMsg: "Error occurs during operation"
                    });
                    that.ajaxService.send(callOptions);
                }
            });
        }
    };
    APIKeysView.prototype.APIGridOnSelectionChanged = function (e) {
        if (e.selectedRowKeys && e.selectedRowKeys[0]) {
            $("#deleteAPiKeyDx").dxButton("instance").option("disabled", !e.selectedRowsData[0].Id);
            $("#editAPIKeyDx").dxButton("instance").option("disabled", !e.selectedRowsData[0].Id);
            var key = e.selectedRowKeys[0];
            var rowIndex = $("#apiGridDx").dxDataGrid("instance").getRowIndexByKey(key);
            this.apiGridSelectedIndex = rowIndex;
        }
        else {
            $("#deleteAPiKeyDx").dxButton("instance").option("disabled", true);
            $("#editAPIKeyDx").dxButton("instance").option("disabled", true);
            this.apiGridSelectedIndex = -1;
        }
    };
    APIKeysView.prototype.AddAPIKey = function () {
        var that = this;
        var callUrl = this.callController + '/AddAPIKey';
        var data = {
            __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
        };
        var callOptions = new AjaxOptions({
            url: callUrl,
            method: AjaxMethod.POST,
            data: data,
            callback: function (response) { that.PopupForm.call(that, response); },
            errorMsg: "Error occurs during operation"
        });
        this.ajaxService.send(callOptions);
    };
    APIKeysView.prototype.EditAPIKey = function () {
        var that = this;
        var callUrl = this.callController + '/EditAPIKey';
        var data = {
            __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
            id: $("#apiGridDx").dxDataGrid("instance").getSelectedRowsData()[0].Id,
        };
        var callOptions = new AjaxOptions({
            url: callUrl,
            method: AjaxMethod.POST,
            data: data,
            callback: function (response) { that.PopupForm.call(that, response); },
            errorMsg: "Error occurs during operation"
        });
        this.ajaxService.send(callOptions);
    };
    APIKeysView.prototype.UpdateAPIKey = function (e) {
        var that = this;
        var result = e.validationGroup.validate();
        if (result.isValid) {
            var callUrl = this.callController + '/EditAPIKeysSubmit';
            var data = {
                __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
                model: {
                    Name: $('#nameDx').dxTextBox('instance').option("value"),
                    Description: $('#descDx').dxTextArea('instance').option("value"),
                    AllowedHosts: $('#hostsDx').dxTextArea('instance').option("value")
                }
            };
            var callOptions = new AjaxOptions({
                url: callUrl,
                method: AjaxMethod.POST,
                data: data,
                callback: function (response) {
                    $("#apiGridDx").dxDataGrid("instance").refresh();
                    $('#apiKeyPopupDx').dxPopup('instance').hide();
                },
                errorCallback: function (response) {
                    if (response.status = "401") {
                        DevExpress.ui.notify(response.responseText, "error", 6000);
                    }
                    else {
                        DevExpress.ui.notify("Error creating API Key", "error", 6000);
                    }
                },
                successMsg: "API Key updated successfully"
            });
            this.ajaxService.send(callOptions);
        }
    };
    APIKeysView.prototype.SetNewAPIKey = function (e) {
        var that = this;
        var result = e.validationGroup.validate();
        if (result.isValid) {
            var callUrl = this.callController + '/AddAPIKeysSubmit';
            var data = {
                __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
                model: {
                    Key: $('#Key').val().toString(),
                    Name: $('#nameDx').dxTextBox('instance').option("value"),
                    UserID: $("#UserIDDx").dxDropDownBox("instance").option('value'),
                    Description: $('#descDx').dxTextArea('instance').option("value"),
                    AllowedHosts: $('#hostsDx').dxTextArea('instance').option("value")
                }
            };
            var callOptions = new AjaxOptions({
                url: callUrl,
                method: AjaxMethod.POST,
                data: data,
                callback: function (response) {
                    $("#apiGridDx").dxDataGrid("instance").refresh();
                    $('#apiKeyPopupDx').dxPopup('instance').hide();
                },
                errorCallback: function (response) {
                    if (response.status = "401") {
                        DevExpress.ui.notify(response.responseText, "error", 6000);
                    }
                    else {
                        DevExpress.ui.notify("Error creating API Key", "error", 6000);
                    }
                },
                successMsg: "API Key registered successfully"
            });
            this.ajaxService.send(callOptions);
        }
    };
    APIKeysView.prototype.PopupForm = function (content, show) {
        if (show === void 0) { show = true; }
        var popup = this.GetPopup();
        if (this.IsMobile()) {
            popup.option('width', '700px');
            popup.option('height', '370px');
        }
        popup.option('contentTemplate', null);
        popup.option('contentTemplate', $(content));
        popup.show();
    };
    APIKeysView.prototype.GetPopup = function () {
        var popup = $("#apiKeyPopupDx").dxPopup("instance");
        return popup;
    };
    return APIKeysView;
}(BaseView));
var View = window.View || {};
document.addEventListener("DOMContentLoaded", function documentReady() {
    this.removeEventListener("DOMContentLoaded", documentReady);
    View = window.View = new APIKeysView();
});
