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 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 CompltedView = (function (_super) {
    __extends(CompltedView, _super);
    function CompltedView() {
        var _this = _super.call(this) || this;
        _this.callController = "/Reports";
        _this.intervalId = null;
        _this.timer = 20;
        _this.ajaxService = new AjaxService();
        var searchParams = new URLSearchParams(window.location.search);
        var hasIFrame = searchParams.has('iframe');
        _this.iframeParamters = hasIFrame ? "&iframe=true" : "";
        console.log(window.location.search);
        console.log(_this.iframeParamters);
        _this.InitToolbarControls();
        var that = _this;
        _this.completedGridDx = $('#completedGridDx').dxDataGrid('instance');
        _this.intervalId = setInterval(function () {
            if (that.timer == 1) {
                that.timer = 21;
                that.completedGridDx.refresh();
            }
            else {
                that.timer--;
                $('#refreshTimeDx').text(that.timer.toString());
            }
        }, 1000);
        $('#refreshUserDx').dxButton('instance').on('click', function () {
            _this.timer = 21;
            _this.completedGridDx.refresh();
        });
        var deleteCompleted = $("#deleteCompletedDx").dxButton("instance");
        deleteCompleted.option('disabled', true);
        deleteCompleted.option().onClick = function (e) {
            that.DeleteCompletedRows(that.completedGridDx.getSelectedRowKeys());
        };
        _this.completedGridDx.option().onRowClick = function (e) {
            if (e.data && e.data.Id) {
                that.completedGridDx.selectRows([e.data.Id], false);
            }
        };
        _this.completedGridDx.option().onSelectionChanged = function (e) {
            if (e.currentDeselectedRowKeys || e.currentSelectedRowKeys) {
                if (e.selectedRowsData && e.selectedRowsData.length > 0) {
                    clearInterval(that.intervalId);
                    that.intervalId = null;
                    $('#refreshUserDx').dxButton('instance').option('disabled', true);
                }
                else {
                    $('#refreshUserDx').dxButton('instance').option('disabled', false);
                    deleteCompleted.option('disabled', true);
                    if (!that.intervalId) {
                        that.intervalId = setInterval(function () {
                            if (that.timer == 1) {
                                that.timer = 21;
                                that.completedGridDx.refresh();
                            }
                            else {
                                that.timer--;
                                $('#refreshTimeDx').text(that.timer.toString());
                            }
                        }, 1000);
                    }
                }
                if (e.selectedRowsData && e.selectedRowsData.length > 1) {
                    for (var i = 0; i < e.selectedRowsData.length; i++) {
                        var deselect = e.selectedRowsData[i].IsDeleteEnabled == false;
                        if (deselect) {
                            e.currentSelectedRowKeys.splice(i, 1);
                            e.component.deselectRows(e.selectedRowsData[i].Id);
                        }
                    }
                }
                if (e.selectedRowsData && e.selectedRowsData.length == 1) {
                    var disabled = e.selectedRowsData[0].IsDeleteEnabled == false;
                    deleteCompleted.option('disabled', disabled);
                    that.CheckReportExecutionRights(e.selectedRowsData[0].ReportViewId, e.selectedRowsData[0].Id, e.selectedRowsData[0].IsDownloadable, e.selectedRowsData[0].ExportFileType);
                }
                else {
                    that.DisableToolbarItems();
                }
            }
        };
        _this.completedGridDx.option().onCellPrepared = function (e) {
            if (e.rowType === 'header' && e.column.command == "select") {
                var commandCell = e.cellElement;
                commandCell.html("Delete");
            }
            if (e.rowType === "data" && e.column.command === 'select' && e.data.IsDeleteEnabled === false) {
                e.cellElement.find('.dx-select-checkbox').dxCheckBox("instance").option("disabled", true);
                e.cellElement.off();
            }
        };
        return _this;
    }
    CompltedView.prototype.Counter = function () {
        if (this.timer == 1) {
            this.timer = 21;
            this.completedGridDx.refresh();
        }
        else {
            this.timer--;
            $('#refreshTimeDx').text(this.timer.toString());
        }
    };
    CompltedView.prototype.InitToolbarControls = function () {
        var that = this;
        this.detailCmdDx = $("#detailCmdDx").dxButton("instance");
        this.sumaryCmdDx = $("#sumaryCmdDx").dxButton("instance");
        this.finishCmdDx = $("#finishCmdDx").dxButton("instance");
        this.vizCmdDx = $("#vizCmdDx").dxButton("instance");
        this.downloadCmdDx = $("#downloadCmdDx").dxButton("instance");
        this.previewCmdDx = $("#previewCmdDx").dxButton("instance");
        this.reReExcuteCmdDx = $("#reReExcuteCmdDx").dxButton("instance");
        this.parametersCmdDx = $("#parametersCmdDx").dxButton("instance");
        if (this.IsDefined(this.detailCmdDx)) {
            this.detailCmdDx.option().onClick = function (e) {
                var data = that.completedGridDx.getSelectedRowsData();
                if (data && data.length === 1) {
                    var roleId = data[0].RoleId == null ? "" : "&roleId=" + data[0].RoleId;
                    window.location.replace("/Visualize/Report?storageId=" + data[0].Id + roleId + "&type=Detail Grid" + that.iframeParamters);
                }
            };
        }
        if (this.IsDefined(this.sumaryCmdDx)) {
            this.sumaryCmdDx.option().onClick = function (e) {
                var data = that.completedGridDx.getSelectedRowsData();
                if (data && data.length === 1) {
                    var roleId = data[0].RoleId == null ? "" : "&roleId=" + data[0].RoleId;
                    window.location.replace("/Visualize/Report?storageId=" + data[0].Id + roleId + "&type=Summary Grid" + that.iframeParamters);
                }
            };
        }
        if (this.IsDefined(this.finishCmdDx)) {
            this.finishCmdDx.option().onClick = function (e) {
                var data = that.completedGridDx.getSelectedRowsData();
                if (data && data.length === 1) {
                    var roleId = data[0].RoleId == null ? "" : "&roleId=" + data[0].RoleId;
                    window.location.replace("/Visualize/Report?storageId=" + data[0].Id + roleId + "&type=Finished Report" + that.iframeParamters);
                }
            };
        }
        if (this.IsDefined(this.vizCmdDx)) {
            this.vizCmdDx.option().onClick = function (e) {
                var data = that.completedGridDx.getSelectedRowsData();
                if (data && data.length === 1) {
                    var roleId = data[0].RoleId == null ? "" : "&roleId=" + data[0].RoleId;
                    window.location.replace("/Visualize/Report?storageId=" + data[0].Id + roleId + "&type=Visualize" + that.iframeParamters);
                }
            };
        }
        if (this.IsDefined(this.downloadCmdDx)) {
            this.downloadCmdDx.option().onClick = function (e) {
                var data = that.completedGridDx.getSelectedRowsData();
                if (data && data.length === 1) {
                    var roleId = data[0].RoleId == null ? "" : "&roleId=" + data[0].RoleId;
                    window.open("/Reports/DownloadReport?storageId=" + data[0].Id + roleId);
                }
            };
        }
        if (this.IsDefined(this.previewCmdDx)) {
            this.previewCmdDx.option().onClick = function (e) {
                var data = that.completedGridDx.getSelectedRowsData();
                if (data && data.length === 1) {
                    var roleId = data[0].RoleId == null ? "" : "&roleId=" + data[0].RoleId;
                    window.location.replace("/Reports/PreviewReport?storageId=" + data[0].Id + roleId);
                }
            };
        }
        if (this.IsDefined(this.reReExcuteCmdDx)) {
            this.reReExcuteCmdDx.option().onClick = function (e) {
                var data = that.completedGridDx.getSelectedRowsData();
                if (data && data.length === 1) {
                    var roleId = data[0].RoleId == null ? "" : "&roleId=" + data[0].RoleId;
                    window.location.replace("/Reports/ReportReExecute?storageId=" + data[0].Id + roleId + that.iframeParamters);
                }
            };
        }
        if (this.IsDefined(this.parametersCmdDx)) {
            this.parametersCmdDx.option().onClick = function (e) {
                var data = that.completedGridDx.getSelectedRowsData();
                if (data && data.length === 1) {
                    View.ShowParamters(data[0].Id, data[0].RoleId);
                }
            };
        }
    };
    CompltedView.prototype.CheckReportExecutionRights = function (reportId, storageId, isDownloadable, type) {
        var that = this;
        if (reportId) {
            this.GetLoadPanelInstance().show();
            var callUrl = this.callController + '/CheckReportExecutionRights';
            var data = {
                __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
                reportId: reportId,
                storageId: storageId
            };
            var callOptions = new AjaxOptions({
                url: callUrl,
                method: AjaxMethod.POST,
                data: data,
                callback: function (d) {
                    if (d && d.ReportId === reportId) {
                        that.detailCmdDx.option('disabled', !(d.Details && !isDownloadable));
                        that.sumaryCmdDx.option('disabled', !(d.Summary && !isDownloadable));
                        that.finishCmdDx.option('disabled', !(d.Finished && !isDownloadable));
                        that.vizCmdDx.option('disabled', !(d.Visualize && !isDownloadable));
                        that.downloadCmdDx.option('disabled', !isDownloadable);
                        that.previewCmdDx.option('disabled', !(isDownloadable && (type === ".PRNX")));
                        that.reReExcuteCmdDx.option('disabled', !d.ReExcute);
                        that.parametersCmdDx.option('disabled', false);
                        that.GetLoadPanelInstance().hide();
                    }
                },
                errorCallback: function (r) {
                    that.detailCmdDx.option('disabled', true);
                    that.sumaryCmdDx.option('disabled', true);
                    that.finishCmdDx.option('disabled', true);
                    that.vizCmdDx.option('disabled', true);
                    that.downloadCmdDx.option('disabled', true);
                    that.previewCmdDx.option('disabled', true);
                    that.reReExcuteCmdDx.option('disabled', true);
                    that.parametersCmdDx.option('disabled', true);
                    that.GetLoadPanelInstance().hide();
                },
                errorMsg: "Error occurs during operation",
            });
            this.ajaxService.send(callOptions);
        }
    };
    CompltedView.prototype.DisableToolbarItems = function () {
        var that = this;
        that.detailCmdDx.option('disabled', true);
        that.sumaryCmdDx.option('disabled', true);
        that.finishCmdDx.option('disabled', true);
        that.vizCmdDx.option('disabled', true);
        that.downloadCmdDx.option('disabled', true);
        that.previewCmdDx.option('disabled', true);
        that.reReExcuteCmdDx.option('disabled', true);
        that.parametersCmdDx.option('disabled', true);
    };
    CompltedView.prototype.GetLoadPanelInstance = function () {
        return $("#loadingDx").dxLoadPanel("instance");
    };
    CompltedView.prototype.DeleteCompletedRows = function (ids) {
        var that = this;
        if (ids && ids.length > 0) {
            var result = DevExpress.ui.dialog.confirm("<strong>Are you sure?</strong>", "Delete");
            result.done(function (dialogResult) {
                if (dialogResult) {
                    var data = {
                        __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
                        keys: ids.join(',')
                    };
                    var callOptions = new AjaxOptions({
                        url: that.callController + '/DeleteCompleted',
                        method: AjaxMethod.POST,
                        data: data,
                        callback: function (response) {
                            that.completedGridDx.refresh();
                        },
                        errorCallback: function (r) {
                            if (r.responseText) {
                                DevExpress.ui.notify(r.responseText, "error", 5000);
                            }
                        },
                        successMsg: "Completed data storages deleted successfully"
                    });
                    that.ajaxService.send(callOptions);
                }
            });
        }
    };
    CompltedView.prototype.ExpresionSubmit = function (e) {
        var that = this;
        var callUrl = this.callController + '/AddExpressionToGrid';
        var data = {
            __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
            DataType: $('#expTypeDx').dxSelectBox('instance').option('value'),
            ColumnName: $('#expColumnNameDx').dxTextBox('instance').option('value'),
            ExpressionString: $('#expStringDx').dxTextArea('instance').option('value'),
        };
        var callOptions = new AjaxOptions({
            url: callUrl,
            method: AjaxMethod.POST,
            data: data,
            callback: function (response) {
                $('#expressionPopup').dxPopup('instance').hide();
                $('#expTypeDx').dxSelectBox('instance').option('value', null),
                    $('#expColumnNameDx').dxTextBox('instance').option('value', null),
                    $('#expStringDx').dxTextArea('instance').option('value', null),
                    that.ReloadGrid();
            },
            errorMsg: "Error occurs during operation",
            successMsg: "New expression column has been added"
        });
        this.ajaxService.send(callOptions);
    };
    CompltedView.prototype.ReloadGrid = function () {
        var that = this;
        var callUrl = this.callController + '/ReloadExpressionGrid';
        var data = {
            __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
        };
        var callOptions = new AjaxOptions({
            url: callUrl,
            method: AjaxMethod.POST,
            data: data,
            callback: function (response) {
                $('#MainGrid').html(response);
            },
            errorMsg: "Error occurs during operation"
        });
        this.ajaxService.send(callOptions);
    };
    CompltedView.prototype.ShowReport = function (storageId, roleId) {
        if (this.IsNotEmpty(storageId)) {
            roleId = roleId === null ? '' : roleId;
            window.open('/Visualize/Report?storageId=' + storageId + '&roleId=' + roleId);
        }
    };
    CompltedView.prototype.ShowParamters = function (storageId, roleId) {
        var that = this;
        if (this.IsNotEmpty(storageId)) {
            var callUrl = this.callController + '/ShowParameters';
            var data = {
                __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
                storageId: storageId,
                roleId: roleId
            };
            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);
        }
    };
    CompltedView.prototype.PopupForm = function (content, show) {
        if (show === void 0) { show = true; }
        var popup = this.GetPopup();
        popup.option('contentTemplate', null);
        popup.option('contentTemplate', $(content));
        popup.show();
    };
    CompltedView.prototype.GetPopup = function () {
        var popup = $('#parametersValuesPopup').dxPopup("instance");
        return popup;
    };
    return CompltedView;
}(BaseView));
var View = window.View || {};
document.addEventListener("DOMContentLoaded", function documentReady() {
    this.removeEventListener("DOMContentLoaded", documentReady);
    View = window.View = new CompltedView();
});
