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 ParameterViewModel = (function () {
    function ParameterViewModel() {
    }
    return ParameterViewModel;
}());

var ReportViewModel = (function () {
    function ReportViewModel() {
    }
    return ReportViewModel;
}());

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 ParameterType;
(function (ParameterType) {
    ParameterType["COMBOBOX"] = "Combobox";
    ParameterType["VALUE"] = "Value";
    ParameterType["DATETIMEPICKER"] = "DateTimePicker";
    ParameterType["IN"] = "IN";
    ParameterType["IN_NO_PARENTHESIS"] = "INNoParenthesis";
})(ParameterType || (ParameterType = {}));
var ParametersPopupType;
(function (ParametersPopupType) {
    ParametersPopupType[ParametersPopupType["Report"] = 0] = "Report";
    ParametersPopupType[ParametersPopupType["InMemory"] = 1] = "InMemory";
    ParametersPopupType[ParametersPopupType["Download"] = 2] = "Download";
    ParametersPopupType[ParametersPopupType["Scheduled"] = 3] = "Scheduled";
})(ParametersPopupType || (ParametersPopupType = {}));
var ParametersView = (function (_super) {
    __extends(ParametersView, _super);
    function ParametersView(containerId, reportDetails, type, paramtersForScheduler) {
        if (type === void 0) { type = ParametersPopupType.Report; }
        if (paramtersForScheduler === void 0) { paramtersForScheduler = false; }
        var _this = _super.call(this) || this;
        _this.callController = "/Parameters";
        _this.currentPage = 1;
        _this.dynamicGridPages = [];
        _this.backBtnId = "#backPageDx";
        _this.nextBtnId = "#nextPageDx";
        _this.submitBtnId = "#submitParamsDx";
        _this.type = ParametersPopupType.Report;
        _this.paramtersForScheduler = false;
        _this.callVariableExec = [];
        _this.callVariableFilter = false;
        _this.popupId = containerId;
        _this.reportDetails = reportDetails;
        _this.currentPage = 1;
        _this.dynamicGridPages = [];
        _this.type = type;
        _this.paramtersForScheduler = paramtersForScheduler;
        _this.ajaxService = new AjaxService();
        return _this;
    }
    ParametersView.prototype.CallVariableFilter = function (e, clientId, isVariableCheck) {
        if (isVariableCheck === void 0) { isVariableCheck = true; }
        var that = this;
        var variableFilterValue = "_VariableFilterValue";
        var value = null;
        if (e && e.value) {
            value = e.value;
        }
        else if (e && e.selectedItem && e.selectedItem.Value) {
            value = e.selectedItem.Value;
        }
        else if (e && e.component) {
            value = e.component.option('value');
        }
        else {
            value = null;
        }
        if (value != null && Array.isArray(e.value)) {
            value = e.value.join('|,|');
        }
        if (value && clientId) {
            that.callVariableExec.push(clientId);
            that.CheckPageStatus();
            this.callVariableFilter = true;
            var decomposition = clientId.split("_");
            var viewModel = new ParameterViewModel();
            viewModel.ClientId = clientId;
            viewModel.Value = value;
            viewModel.VariableFilter = true;
            viewModel.VariableFilterValue = value;
            $('#' + clientId + variableFilterValue).val(value);
            var callUrl = this.callController + (isVariableCheck ? '/VariableFilterCheck' : '/ByParameterCheck');
            var data = {
                __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
                parameterValue: viewModel,
                reportName: that.reportDetails.Name,
                conID: that.reportDetails.ConnectionId
            };
            var callOptions = new AjaxOptions({
                url: callUrl,
                method: AjaxMethod.POST,
                data: data,
                callback: function (result) {
                    var that2 = that;
                    if (Array.isArray(result)) {
                        var models = result;
                        for (var i = 0; i < models.length; i++) {
                            var disabled = !models[i].EnabledByParameter;
                            var containerId = models[i].ClientId + '_Container';
                            var containerCss = disabled ? 'none' : '';
                            var updateValue = models[i].UpdateDefaultValue;
                            $("#" + containerId).css('display', containerCss);
                            switch (models[i].ClientType) {
                                case ParameterType.COMBOBOX:
                                    $("#" + models[i].ClientId).dxSelectBox("instance").option("disabled", disabled);
                                    $("#" + models[i].ClientId).dxSelectBox("instance").option("visible", !disabled);
                                    if (updateValue) {
                                        $("#" + models[i].ClientId).dxSelectBox("instance").option("value", models[i].DefaultValue);
                                    }
                                    break;
                                case ParameterType.DATETIMEPICKER:
                                    $("#" + models[i].ClientId).dxDateBox("instance").option("disabled", disabled);
                                    $("#" + models[i].ClientId).dxDateBox("instance").option("visible", !disabled);
                                    if (updateValue) {
                                        $("#" + models[i].ClientId).dxDateBox("instance").option("value", models[i].DefaultValue);
                                    }
                                    break;
                                case ParameterType.VALUE:
                                    $("#" + models[i].ClientId).dxTextBox("instance").option("disabled", disabled);
                                    $("#" + models[i].ClientId).dxTextBox("instance").option("visible", !disabled);
                                    if (updateValue) {
                                        $("#" + models[i].ClientId).dxTextBox("instance").option("value", models[i].DefaultValue);
                                    }
                                    break;
                                case ParameterType.IN:
                                case ParameterType.IN_NO_PARENTHESIS:
                                    $("#" + models[i].ClientId).dxList("instance").option("disabled", disabled);
                                    $("#" + models[i].ClientId + "Values").dxDataGrid("instance").option("disabled", disabled);
                                    $("#" + models[i].ClientId + "newText").dxTextBox("instance").option("disabled", disabled);
                                    $("#" + models[i].ClientId + "newValue").dxButton("instance").option("disabled", disabled);
                                    $("#" + models[i].ClientId + "addValue").dxButton("instance").option("disabled", disabled);
                                    $("#" + models[i].ClientId + "addAll").dxButton("instance").option("disabled", disabled);
                                    $("#" + models[i].ClientId + "delAll").dxButton("instance").option("disabled", disabled);
                                    $("#" + models[i].ClientId + "delValue").dxButton("instance").option("disabled", disabled);
                                    $("#" + models[i].ClientId).dxList("instance").option("visible", !disabled);
                                    $("#" + models[i].ClientId + "Values").dxDataGrid("instance").option("visible", !disabled);
                                    $("#" + models[i].ClientId + "newText").dxTextBox("instance").option("visible", !disabled);
                                    $("#" + models[i].ClientId + "newValue").dxButton("instance").option("visible", !disabled);
                                    $("#" + models[i].ClientId + "addValue").dxButton("instance").option("visible", !disabled);
                                    $("#" + models[i].ClientId + "addAll").dxButton("instance").option("visible", !disabled);
                                    $("#" + models[i].ClientId + "delAll").dxButton("instance").option("visible", !disabled);
                                    $("#" + models[i].ClientId + "delValue").dxButton("instance").option("visible", !disabled);
                                default:
                                    break;
                            }
                        }
                    }
                    that.callVariableFilter = false;
                    that.callVariableExec.pop();
                    that.CheckPageStatus();
                },
                errorCallback: function (result) {
                    that.callVariableExec.pop();
                    that.CheckPageStatus();
                },
                errorMsg: "Error occurs during operation",
            });
            this.ajaxService.send(callOptions);
        }
    };
    ParametersView.prototype.GetDonwloadType = function () {
        return this.donwloadType;
    };
    ParametersView.prototype.SubmitParamters = function () {
        var that = this;
        this.Loading().show();
        var paramters = this.GetWizardParameters();
        var data = {
            __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
            viewParameters: paramters,
            reportQuery: that.reportDetails
        };
        if (this.type === ParametersPopupType.Download && this.IsDefined($("#downloadFileTypeDx").dxSelectBox('instance'))) {
            data["downloadType"] = $("#downloadFileTypeDx").dxSelectBox('instance').option('value');
        }
        if (this.paramtersForScheduler) {
            if (this.type === ParametersPopupType.Download && this.IsDefined($("#downloadFileTypeDx").dxSelectBox('instance'))) {
                this.donwloadType = $("#downloadFileTypeDx").dxSelectBox('instance').option('value');
            }
            that.GetPopup().hide();
            that.Loading().hide();
            return;
        }
        var callOptions = new AjaxOptions({
            url: this.GetSubmitAction(this.type),
            method: AjaxMethod.POST,
            data: data,
            callback: function (d) {
                that.GetPopup().hide();
                that.GetPopup().option('contentTemplate', null);
                if (that.type === ParametersPopupType.InMemory) {
                    DevExpress.ui.notify("Please Wait. Report will soon finish execution and redirect you to result page", "success", 15000);
                    document.location.href = d;
                }
                else {
                    that.Loading().hide();
                }
            },
            errorCallback: function (d) {
                DevExpress.ui.notify("Error running report. Check error logs for additional information.", "error", 5000);
                that.Loading().hide();
            },
            successMsg: that.type === ParametersPopupType.InMemory ? null : "The report has been sent for execution and will be on the Completed page when available.",
        });
        this.ajaxService.send(callOptions);
    };
    ParametersView.prototype.GetSubmitAction = function (type) {
        switch (type) {
            case ParametersPopupType.InMemory:
                return this.callController + '/Execute';
            case ParametersPopupType.Download:
                return this.callController + '/Download';
            case ParametersPopupType.Report:
                return this.callController + '/Submit';
            default:
                throw new Error('Not supported ParametersPopupType');
        }
    };
    ParametersView.prototype.GetWizardParameters = function () {
        var variableFilter = "_VariableFilter";
        var order = "_Order";
        var variableFilterValue = "_VariableFilterValue";
        var dynamicDefault = "_IsDynamicDefault";
        var defaultValue = "_DefaultValue";
        var parameterPage = "_Page";
        var parameterType = "_Type";
        var ctrls = $('input[id*="parameterClientId"]');
        var paramters = [];
        if (ctrls.length > 0) {
            ctrls.each(function (i) {
                var ctrlName = $(ctrls[i]).val().toString();
                var decomposition = ctrlName.split("_");
                if (decomposition.length > 0 && decomposition.length === 3) {
                    var value = null;
                    try {
                        switch (decomposition[1]) {
                            case ParameterType.COMBOBOX:
                                value = $("#" + ctrlName).dxSelectBox("instance").option("value");
                                break;
                            case ParameterType.DATETIMEPICKER:
                                value = $("#" + ctrlName).dxDateBox("instance").option("value");
                                break;
                            case ParameterType.VALUE:
                                value = $("#" + ctrlName).dxTextBox("instance").option("value");
                                break;
                            case ParameterType.IN:
                            case ParameterType.IN_NO_PARENTHESIS:
                                value = $("#" + ctrlName).dxList("instance").option("items").join('|,|');
                                break;
                            default:
                                break;
                        }
                        var viewModel = new ParameterViewModel();
                        viewModel.ClientId = ctrlName;
                        viewModel.Value = value;
                        viewModel.Order = parseInt($('#' + ctrlName + order).val().toString());
                        viewModel.VariableFilter = $('#' + ctrlName + variableFilter).val() === "True";
                        viewModel.VariableFilterValue = $('#' + ctrlName + variableFilterValue).val().toString();
                        viewModel.IsDynamicDefault = $('#' + ctrlName + dynamicDefault).val() === "True";
                        viewModel.DefaultValue = $('#' + ctrlName + defaultValue).val().toString();
                        viewModel.Page = parseInt($('#' + ctrlName + parameterPage).val().toString());
                        viewModel.ClientType = $('#' + ctrlName + parameterType).val().toString();
                        paramters.push(viewModel);
                    }
                    catch (err) {
                        console.log(err);
                    }
                }
            });
        }
        return paramters;
    };
    ParametersView.prototype.GetCurrentReportName = function () {
        return this.reportDetails.Name;
    };
    ParametersView.prototype.GetCurrentConnectionProfile = function () {
        return this.reportDetails.ConnectionId;
    };
    ParametersView.prototype.AddAll = function (gridId, listId) {
        if (gridId && listId) {
            var grid_1 = $('#' + gridId).dxDataGrid("instance");
            var list_1 = $('#' + listId).dxList("instance");
            if (grid_1 && list_1) {
                grid_1.option('remoteOperations', false);
                grid_1.option('scrolling.mode', 'standard');
                grid_1.getDataSource().load().done(function (data) {
                    var items = data.map(function (m) { return m.Value; });
                    var existedItems = list_1.option('items');
                    if (existedItems.length > 0) {
                        for (var i = 0; i < existedItems.length; i++) {
                            if (items.indexOf(existedItems[i]) === -1) {
                                items.push(existedItems[i]);
                            }
                        }
                    }
                    list_1.option('items', []);
                    list_1.option('items', items);
                    grid_1.option('remoteOperations', true);
                    grid_1.option('scrolling.mode', 'infinite');
                }).fail(function () {
                    grid_1.option('remoteOperations', true);
                    grid_1.option('scrolling.mode', 'infinite');
                });
            }
        }
    };
    ParametersView.prototype.AddNewValue = function (textId, listId, gridId, RestrictedList) {
        if (textId && listId) {
            var newText = $('#' + textId).dxTextBox("instance");
            var list = $('#' + listId).dxList("instance");
            var grid = $('#' + gridId).dxDataGrid("instance");
            if (newText && list) {
                var value = newText.option('value');
                var items_1 = list.option('items');
                var restrictedItems_1 = [];
                var existedItems_1 = [];
                if (RestrictedList == true) {
                    grid.getDataSource().load().done(function (data) {
                        existedItems_1 = data.map(function (m) { return m.Value; });
                    }).fail(function () {
                    });
                }
                if (value) {
                    if (value.includes(',')) {
                        var individualValues = value.split(',');
                        individualValues.forEach(function (individualValue) {
                            var trimmedValue = individualValue.trim();
                            var upperValue = trimmedValue.toUpperCase();
                            if (items_1.indexOf(trimmedValue) === -1) {
                                if (RestrictedList === true) {
                                    var match = existedItems_1.find(function (ei) { return ei.toUpperCase() === upperValue; });
                                    if (match) {
                                        items_1.push(match);
                                    }
                                    else {
                                        restrictedItems_1.push(trimmedValue);
                                    }
                                }
                                else {
                                    items_1.push(trimmedValue);
                                }
                            }
                        });
                    }
                    else {
                        var trimmedValue = value.trim();
                        if (items_1.indexOf(trimmedValue) === -1) {
                            var upperValue_1 = trimmedValue.toUpperCase();
                            if (RestrictedList === true) {
                                var match = existedItems_1.find(function (ei) { return ei.toUpperCase() === upperValue_1; });
                                if (match) {
                                    items_1.push(match);
                                }
                                else {
                                    restrictedItems_1.push(trimmedValue);
                                }
                            }
                            else {
                                items_1.push(trimmedValue);
                            }
                        }
                    }
                    list.option('items', items_1);
                    if (restrictedItems_1.length > 0) {
                        var itemsShowing = restrictedItems_1.slice(0, 10).join(', ');
                        DevExpress.ui.dialog.alert("There were ".concat(restrictedItems_1.length, " values restricted. Up to 10 of the values will be shown: ").concat(itemsShowing, "."), "Restricted Items");
                    }
                }
            }
        }
    };
    ParametersView.prototype.AddValue = function (gridId, listId) {
        if (gridId && listId) {
            var grid = $('#' + gridId).dxDataGrid("instance");
            var list = $('#' + listId).dxList("instance");
            if (grid && list) {
                var values = grid.getSelectedRowsData().map(function (m) { return m.Value; });
                var items = list.option('items');
                if (values.length > 0) {
                    for (var i = 0; i < values.length; i++) {
                        if (items.indexOf(values[i]) === -1) {
                            items.push(values[i]);
                        }
                    }
                    list.option('items', items);
                }
            }
        }
    };
    ParametersView.prototype.RemoveValue = function (gridId, listId) {
        if (gridId && listId) {
            var grid = $('#' + gridId).dxDataGrid("instance");
            var list = $('#' + listId).dxList("instance");
            if (grid && list) {
                var items = list.option('items');
                var toremove = list.option('selectedItems');
                if (toremove.length > 0) {
                    for (var i = 0; i < toremove.length; i++) {
                        var index = items.indexOf(toremove[i]);
                        if (index !== -1) {
                            items.splice(index, 1);
                        }
                    }
                    list.option('items', items);
                }
            }
        }
    };
    ParametersView.prototype.RemoveAll = function (gridId, listId) {
        if (gridId && listId) {
            var grid = $('#' + gridId).dxDataGrid("instance");
            var list = $('#' + listId).dxList("instance");
            if (grid && list) {
                list.option('items', []);
            }
        }
    };
    ParametersView.prototype.GetParameters = function () {
        var that = this;
        var data = {
            __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
            reportName: this.reportDetails.Name,
            conID: this.reportDetails.ConnectionId
        };
        var callOptions = new AjaxOptions({
            url: that.type === ParametersPopupType.Download ? this.callController + '/GetParametersForDownloads' : this.callController + '/GetParameters',
            method: AjaxMethod.POST,
            data: data,
            callback: function (d) { that.PopupForm.call(that, d, "Parameters"); that.Loading().hide(); },
            errorMsg: "Error occurs during operation"
        });
        if (this.type !== ParametersPopupType.Download && this.reportDetails.Name) {
            var callOptionsForCheck = new AjaxOptions({
                url: this.callController + '/HasParameters',
                method: AjaxMethod.POST,
                data: data,
                callback: function (d) {
                    if (!d) {
                        that.SubmitParamters();
                    }
                    else {
                        that.ajaxService.send(callOptions);
                    }
                    that.Loading().show();
                },
                errorMsg: "Error occurs during operation"
            });
            this.ajaxService.send(callOptionsForCheck);
        }
        if (this.type === ParametersPopupType.Download && this.reportDetails.Name) {
            this.ajaxService.send(callOptions);
        }
    };
    ParametersView.prototype.PopupForm = function (content, title, 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));
        if (show) {
            popup.show();
        }
        this.SetupPaging();
    };
    ParametersView.prototype.GetPopup = function () {
        var popup = $(this.popupId).dxPopup("instance");
        return popup;
    };
    ParametersView.prototype.ValidateList = function (listId, listValidatorId, group) {
        if (listId && listValidatorId) {
            $("#" + listValidatorId).dxValidator({
                validationGroup: group,
                adapter: {
                    getValue: function () {
                        var list = $("#" + listId).dxList("option", "items");
                        return list.length > 0 || $("#" + listId).dxList("option", "disabled");
                    },
                    applyValidationResults: function (e) {
                        $("#" + listId).css({ "border": e.isValid ? "none" : "1px solid red" });
                    },
                },
                validationRules: [{
                        type: "required",
                        message: 'Specify at least one item!'
                    }]
            });
        }
    };
    ParametersView.prototype.SetDynamicPage = function (skipId, gridId, pageId, listId) {
        var that = this;
        var grid = $("#" + gridId).dxDataGrid("instance");
        $('#' + listId).on("dxdblclick", function (e) {
            that.RemoveValueFromList(e.currentTarget.id);
        });
        var firstCallEnd = $('#skipFirstCallFor' + skipId).val() === 'True';
        if (firstCallEnd && this.IsNotEmpty(skipId) && this.IsNotEmpty(gridId) && this.IsNotEmpty(pageId)) {
            $('#skipFirstCallFor' + skipId).val('False');
            this.dynamicGridPages.push({ page: parseInt(pageId), grid: gridId });
            if (pageId === "1") {
                grid.refresh().done(function () { that.CheckColumnVisibility("#" + gridId); });
            }
        }
        grid.repaint();
    };
    ParametersView.prototype.RemoveValueFromList = function (listId) {
        if (listId) {
            var list = $('#' + listId).dxList("instance");
            var toRemove = list.option('selectedItems');
            if (list && toRemove.length > 0) {
                var items = list.option('items');
                var index = items.indexOf(toRemove[0]);
                if (index !== -1) {
                    items.splice(index, 1);
                }
                list.option('items', items);
            }
        }
    };
    ParametersView.prototype.AddValueToList = function (e, listId) {
        if (e && e.data && listId) {
            var list = $('#' + listId).dxList("instance");
            if (list) {
                var items = list.option('items');
                if (items.indexOf(e.data.Value) === -1) {
                    items.push(e.data.Value);
                }
                list.option('items', items);
            }
        }
    };
    ParametersView.prototype.CheckColumnVisibility = function (gridId) {
        var _this = this;
        var grid = $(gridId).dxDataGrid("instance");
        var descriptionExsits = grid.getDataSource().items().filter(function (d) { return _this.IsNotEmpty(d.Description); });
        if (this.IsDefined(descriptionExsits) && descriptionExsits.length > 0) {
            grid.columnOption("Description", "visible", true);
            grid.repaint();
        }
    };
    ParametersView.prototype.SetupPaging = function () {
        var _this = this;
        var that = this;
        this.backBtn = $(this.backBtnId).dxButton("instance");
        this.backBtn.option("onClick", function (e) {
            var that2 = that;
            $('#page' + that.currentPage).css("display", "none");
            that.currentPage--;
            if (that.currentPage <= 0) {
                that.currentPage = 1;
            }
            if (that.currentPage != 1) {
                var Parameterfound = void 0;
                for (var i = that.currentPage + 1; i >= 1; i--) {
                    var paramtersOnPage = that.GetWizardParameters().filter(function (m) { return m.Page == that.currentPage; });
                    if (!paramtersOnPage || paramtersOnPage.length <= 0) {
                        that.currentPage--;
                    }
                    else {
                        for (var j = 0; j < paramtersOnPage.length; j++) {
                            var visible = that.GetParamterVisibility(paramtersOnPage[j]);
                            if (!visible) {
                                continue;
                            }
                            else {
                                Parameterfound = true;
                                break;
                            }
                        }
                        if (!Parameterfound) {
                            that.currentPage--;
                        }
                        else {
                            break;
                        }
                    }
                }
            }
            if (that.currentPage <= 1) {
                that.currentPage = 1;
            }
            var dynamicPage = that.dynamicGridPages.filter(function (m) { return m.page === that.currentPage; });
            if (dynamicPage && dynamicPage.length > 0) {
                var interval = setInterval(function () {
                    if (!that.callVariableFilter) {
                        for (var i = 0; i < dynamicPage.length; i++) {
                            var id = "#" + dynamicPage[i].grid;
                            var grid = $(id).dxDataGrid("instance");
                            if (grid && !grid.option('disabled')) {
                                var newIdToCall = id;
                                clearInterval(interval);
                                grid.refresh().done(function () {
                                    that2.CheckColumnVisibility(newIdToCall);
                                });
                            }
                        }
                    }
                }, 250);
            }
            $('#page' + that.currentPage).css("display", "flex");
            that.CheckPageStatus();
        });
        this.nextBtn = $(this.nextBtnId).dxButton("instance");
        this.nextBtn.option("onClick", function (e) {
            var that2 = that;
            if (that.IsValidationSuccessful(that.currentPage)) {
                $('#page' + that.currentPage).css("display", "none");
                var lastPage = parseInt($('#lastPage').val().toString());
                that.currentPage++;
                var Parameterfound = void 0;
                for (var i = that.currentPage - 1; i <= lastPage; i++) {
                    var paramtersOnPage = that.GetWizardParameters().filter(function (m) { return m.Page == that.currentPage; });
                    if (!paramtersOnPage || paramtersOnPage.length <= 0) {
                        that.currentPage++;
                    }
                    else {
                        for (var j = 0; j < paramtersOnPage.length; j++) {
                            var visible = that.GetParamterVisibility(paramtersOnPage[j]);
                            if (!visible) {
                                continue;
                            }
                            else {
                                Parameterfound = true;
                                break;
                            }
                        }
                        if (!Parameterfound) {
                            that.currentPage++;
                        }
                        else {
                            break;
                        }
                    }
                }
                if (that.currentPage >= lastPage) {
                    that.currentPage = lastPage;
                }
                var dynamicPage = that.dynamicGridPages.filter(function (m) { return m.page === that.currentPage; });
                if (dynamicPage && dynamicPage.length > 0) {
                    var interval = setInterval(function () {
                        if (!that.callVariableFilter) {
                            for (var i = 0; i < dynamicPage.length; i++) {
                                var id = "#" + dynamicPage[i].grid;
                                var grid = $(id).dxDataGrid("instance");
                                if (grid && !grid.option('disabled')) {
                                    var newIdToCall = id;
                                    clearInterval(interval);
                                    grid.refresh().done(function () {
                                        that2.CheckColumnVisibility(newIdToCall);
                                    });
                                }
                            }
                        }
                    }, 250);
                }
                $('#page' + that.currentPage).css("display", "flex");
                that.CheckPageStatus();
            }
            else {
                DevExpress.ui.notify("Enter required value(s) on page", "error", 3000);
            }
        });
        this.submitBtn = $(this.submitBtnId).dxButton("instance");
        this.submitBtn.option("onClick", function (e) {
            var that = _this;
            if (that.IsValidationSuccessful(that.currentPage)) {
                that.SubmitParamters();
                if (!_this.paramtersForScheduler) {
                    that.CheckPageStatus();
                }
            }
        });
        if (this.paramtersForScheduler) {
            this.submitBtn.option('text', 'Schedule');
        }
        this.CheckPageStatus();
    };
    ParametersView.prototype.GetParamterVisibility = function (paramter) {
        var containerId = paramter.ClientId + '_Container';
        var temp = $("#" + containerId).css('display');
        var isVisible = $("#" + containerId).css('display') == 'none';
        return !isVisible;
    };
    ParametersView.prototype.IsValidationSuccessful = function (currentPage) {
        var groups = DevExpress.validationEngine.groups;
        if (groups) {
            var groupExists = groups.find(function (g) { return g.group === currentPage.toString(); });
            if (groupExists) {
                var result = DevExpress.validationEngine.validateGroup(currentPage.toString());
                return result.isValid;
            }
            else {
                return true;
            }
        }
        else {
            console.log("Parameters: Validation groups not setup.");
            return true;
        }
    };
    ParametersView.prototype.CheckPageStatus = function () {
        var lastPage = parseInt($('#lastPage').val().toString());
        $('#currentPage').val(this.currentPage);
        if (this.backBtn) {
            this.backBtn.option('disabled', this.currentPage === 1);
        }
        if (this.nextBtn) {
            this.nextBtn.option('disabled', lastPage === this.currentPage || this.callVariableExec.length !== 0);
        }
        if (this.submitBtn) {
            this.submitBtn.option('disabled', !(lastPage === this.currentPage));
        }
    };
    return ParametersView;
}(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 ReportsView = (function (_super) {
    __extends(ReportsView, _super);
    function ReportsView() {
        var _this = _super.call(this) || this;
        _this.callController = "/Reports";
        _this.ctrlAdded = false;
        _this.zoomMin = 5;
        _this.zoomMax = 60;
        _this.zoomCurrent = 0;
        _this.disableClick = true;
        _this.ajaxService = new AjaxService();
        _this.InitToolbarControls();
        return _this;
    }
    ReportsView.prototype.SchedulerZoomIn = function () {
        this.zoomCurrent = $("#schedulerDx").dxScheduler("instance").option('cellDuration');
        this.zoomCurrent -= 5;
        $("#schedulerDx").dxScheduler("instance").option('cellDuration', this.zoomCurrent);
        $("#schedulerDx").dxScheduler("instance").repaint();
        $("#zoomOutDx").dxButton("instance").option('disabled', (this.zoomCurrent >= this.zoomMax));
        $("#zoomInDx").dxButton("instance").option('disabled', (this.zoomCurrent <= this.zoomMin));
    };
    ReportsView.prototype.SchedulerZoomOut = function () {
        this.zoomCurrent = $("#schedulerDx").dxScheduler("instance").option('cellDuration');
        this.zoomCurrent += 5;
        $("#schedulerDx").dxScheduler("instance").option('cellDuration', this.zoomCurrent);
        $("#schedulerDx").dxScheduler("instance").repaint();
        $("#zoomOutDx").dxButton("instance").option('disabled', (this.zoomCurrent >= this.zoomMax));
        $("#zoomInDx").dxButton("instance").option('disabled', (this.zoomCurrent <= this.zoomMin));
    };
    ReportsView.prototype.SchedulerAppointmentRendered = function (e) {
        var that = this;
        if (e && e.appointmentData) {
            var callUrl = this.callController + '/GetReportStatus';
            var data = {
                __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
                report: e.appointmentData
            };
            var callOptions = new AjaxOptions({
                url: callUrl,
                method: AjaxMethod.POST,
                data: data,
                callback: function (d) {
                    if (d.Id && d.Color) {
                        var color = ';background-color:' + d.Color + "!important;";
                        var currentStyle = e.appointmentElement.attr("style");
                        currentStyle += color;
                        e.appointmentElement.attr("style", currentStyle);
                    }
                },
                errorMsg: "Error occurs during operation"
            });
            this.ajaxService.send(callOptions);
        }
    };
    ReportsView.prototype.SchedulerForm = function (e) {
        var that = this;
        var popup = e.popup;
        popup.option('position', { my: { x: 'center', y: 'top' }, at: { x: 'center', y: 'top' }, of: window });
        popup.option('minWidth', this.IsMobile() ? '700px' : '1000px');
        if (this.IsMobile()) {
            popup.option('height', '370px');
        }
        popup.on("shown", function () {
            var form = e.form;
            if (!that.IsDefined(e.appointmentData.AssignmentId)) {
                e.appointmentData["AssignmentId"] = null;
            }
            if (!that.IsDefined(e.appointmentData.ActionType)) {
                e.appointmentData["ActionType"] = null;
            }
            if (!that.IsDefined(e.appointmentData.Paramters)) {
                e.appointmentData["Paramters"] = null;
            }
            if (!that.IsDefined(e.appointmentData.Paramters)) {
                e.appointmentData["Emails"] = null;
            }
            var ds = {
                loadMode: "raw",
                key: "Id",
                load: function (e) {
                    return $.getJSON(that.callController + "/GetReportsForSchedule");
                }
            };
            var formsItems = form.option("items");
            if (that.IsDefined(form) && that.ctrlAdded) {
                formsItems.pop();
            }
            if (that.IsDefined(formsItems)) {
                if (formsItems[0].items && formsItems[0].items.length == 7) {
                    formsItems[0].items.pop();
                }
            }
            var group = that.GetAppointmentReportAssignmentGroup();
            var assignmentCtrl = that.GetAssignmentGrid(ds, that, group, form, e.appointmentData);
            var actionsCtrl = that.GetActionsDropDown(that, group, form, e.appointmentData);
            var paramBtnCtrl = that.GetParamtersButton(that, form, group);
            var paramCtrl = that.GetParamters(that);
            var donwloadTypeCtrl = that.GetDonwloadType(that);
            var reportNameCtrl = that.GetReportName(that);
            var emailsCtrl = that.GetEmails(that);
            group.items.push(emailsCtrl);
            group.items.push(assignmentCtrl);
            group.items.push(actionsCtrl);
            group.items.push(paramBtnCtrl);
            group.items.push(paramCtrl);
            group.items.push(donwloadTypeCtrl);
            group.items.push(reportNameCtrl);
            formsItems.push(group);
            form.endUpdate();
            that.ctrlAdded = true;
            form.repaint();
        });
    };
    ReportsView.prototype.GetEmails = function (that) {
        return {
            dataField: "Emails",
            editorType: "dxTextBox",
            label: { text: 'Notify Emails (separate by semicolon)', visible: true },
            visible: true,
            colSpan: 9
        };
    };
    ReportsView.prototype.GetReportName = function (that) {
        return {
            dataField: "ReportName",
            editorType: "dxTextBox",
            label: { text: null, visible: false },
            visible: false
        };
    };
    ReportsView.prototype.GetParamters = function (that) {
        return {
            dataField: "ParametersJSON",
            editorType: "dxTextBox",
            label: { text: null, visible: false },
            visible: false
        };
    };
    ReportsView.prototype.GetDonwloadType = function (that) {
        return {
            dataField: "ExportFileType",
            editorType: "dxTextBox",
            label: { text: null, visible: false },
            visible: false
        };
    };
    ReportsView.prototype.GetParamtersButton = function (that, form, group) {
        return {
            dataField: "",
            itemType: "button",
            label: { text: null, visible: false },
            colSpan: 2,
            buttonOptions: {
                text: "Parameters",
                disabled: true,
                width: '100%',
                onClick: function () {
                    var gridRow = $('#smGridDx').dxDataGrid('instance').getSelectedRowsData()[0];
                    var assignmentId = form.getEditor('AssignmentId').option('value');
                    var isDownload = form.getEditor('ActionType').option('value').indexOf('Download') !== -1;
                    var reportType = isDownload ? ParametersPopupType.Download : ParametersPopupType.Report;
                    form.updateData("ReportName", gridRow.Name);
                    var reportDetails = new ReportViewModel();
                    reportDetails.ConnectionId = gridRow.ConnectionId;
                    reportDetails.Name = gridRow.Name;
                    reportDetails.Type = gridRow.Type;
                    reportDetails.RoleId = gridRow.RoleId;
                    reportDetails.ViewId = gridRow.ViewId;
                    that.Parameters = new ParametersView("#reportsParamtersPopup", reportDetails, reportType, true);
                    that.Parameters.GetPopup().option("onHiding", function () {
                        var count = that.Parameters.GetWizardParameters().length;
                        var paramters = JSON.stringify(that.Parameters.GetWizardParameters());
                        if (isDownload) {
                            count++;
                            form.updateData("ExportFileType", that.Parameters.GetDonwloadType());
                        }
                        form.updateData("ParametersJSON", paramters);
                        group.items[3].buttonOptions["disabled"] = true;
                        group.items[3].buttonOptions["text"] = "Paramters (" + count + ")";
                        that.Parameters = null;
                        that.SetupPopupConfiguration();
                        form.repaint();
                    });
                    that.Parameters.GetParameters();
                }
            }
        };
    };
    ReportsView.prototype.GetActionsDropDown = function (that, group, form, appointmentData) {
        return {
            dataField: "ActionType",
            editorType: "dxSelectBox",
            label: { text: null, visible: false },
            colSpan: 2,
            editorOptions: {
                items: that.IsDefined(appointmentData.ActionType) ? [{ Id: appointmentData.ActionType, Value: appointmentData.ActionType }] : null,
                valueExpr: "Id",
                deferRendering: false,
                placeholder: "Select an action...",
                displayExpr: function (item) {
                    return item && item.Value;
                },
                showClearButton: true,
                onValueChanged: function (e) {
                    if (e && e.value) {
                        form.updateData("ActionType", e.value);
                        var url = that.callController + "/HasParameters";
                        url += "?key=" + form.getEditor('AssignmentId').option('value');
                        url += "&actionType=" + e.value;
                        $.getJSON(url, function (data) {
                            group.items[3].buttonOptions["disabled"] = !data;
                            that.SetupPopupConfiguration();
                            form.repaint();
                        });
                    }
                }
            }
        };
    };
    ReportsView.prototype.GetAssignmentGrid = function (ds, that, group, form, appointmentData) {
        return {
            dataField: "AssignmentId",
            editorType: "dxDropDownBox",
            label: { text: null, visible: false },
            colSpan: 5,
            editorOptions: {
                valueExpr: "Id",
                deferRendering: false,
                placeholder: "Select a report...",
                displayExpr: function (item) {
                    return item && item.Name + " | " + item.ConnectionName + " | " + item.Role + " | " + item.Type;
                },
                showClearButton: true,
                dataSource: ds,
                dropDownOptions: {
                    height: "400px",
                    width: "700px",
                },
                onOpened: function (e) { $('#smGridDx').dxDataGrid('instance').repaint(); },
                contentTemplate: function (e) {
                    var value = e.component.option("value"), $dataGrid = $("<div id='smGridDx'>").dxDataGrid({
                        dataSource: e.component.getDataSource(),
                        allowColumnResizing: true,
                        columns: [{ dataField: "Name", width: 340 }, "ConnectionName", "Role", "Type"],
                        hoverStateEnabled: true,
                        paging: { enabled: false, },
                        filterRow: { visible: true },
                        scrolling: { mode: "standard" },
                        selection: { mode: "single" },
                        selectedRowKeys: [value],
                        height: "100%",
                        width: "100%",
                        onSelectionChanged: function (selectedItems) {
                            var keys = selectedItems.selectedRowKeys, hasSelection = keys.length;
                            e.component.option("value", hasSelection ? keys[0] : null);
                            form.updateData("AssignmentId", hasSelection ? keys[0].toString() : null);
                            if (hasSelection) {
                                $.getJSON(that.callController + "/GetReportActionType?key=" + keys[0], function (jsonData) {
                                    group.items[2].editorOptions["items"] = jsonData;
                                    that.SetupPopupConfiguration();
                                    form.repaint();
                                });
                            }
                        }
                    });
                    var dataGrid = $dataGrid.dxDataGrid("instance");
                    e.component.on("valueChanged", function (args) {
                        dataGrid.selectRows(args.value, false);
                        e.component.close();
                    });
                    return $dataGrid;
                }
            },
        };
    };
    ReportsView.prototype.GetAppointmentReportAssignmentGroup = function () {
        return {
            colCount: 9,
            colSpan: 2,
            itemType: "group",
            caption: "Reports Assignment",
            items: [],
        };
    };
    ReportsView.prototype.SetupPopupConfiguration = function () {
        var popup = $('#schedulerDx .dx-scheduler-appointment-popup').dxPopup('instance');
        popup.option('position', { my: { x: 'center', y: 'top' }, at: { x: 'center', y: 'top' }, of: window });
        popup.option('minWidth', this.IsMobile() ? '700px' : '1000px');
        if (this.IsMobile()) {
            popup.option('height', '370px');
        }
        popup.option('position', { my: { x: 'center', y: 'top' }, at: { x: 'center', y: 'top' }, of: window });
        popup.endUpdate();
        popup.repaint();
    };
    ReportsView.prototype.QueueParamters = function (reportDetails, e) {
        if (e === void 0) { e = null; }
        var that = this;
        if (!this.disableClick && e.event && e.event.currentTarget) {
            e.event.preventDefault();
            e.event.stopPropagation();
            return;
        }
        this.disableClick = false;
        var clear = setTimeout(function () {
            that.disableClick = true;
            clearInterval(clear);
        }, 3000);
        this.Parameters = new ParametersView("#reportsParamtersPopup", reportDetails, ParametersPopupType.Report);
        this.Parameters.GetParameters();
        this.Parameters.GetPopup().option("hiding", function () {
            that.Parameters = null;
        });
    };
    ReportsView.prototype.DownloadParamters = function (reportDetails, e) {
        if (e === void 0) { e = null; }
        var that = this;
        if (!this.disableClick && e.event && e.event.currentTarget) {
            e.event.preventDefault();
            e.event.stopPropagation();
            return;
        }
        this.disableClick = false;
        var clear = setTimeout(function () {
            that.disableClick = true;
            clearInterval(clear);
        }, 3000);
        this.Parameters = new ParametersView("#reportsParamtersPopup", reportDetails, ParametersPopupType.Download);
        this.Parameters.GetParameters();
        this.Parameters.GetPopup().option("hiding", function () {
            that.Parameters = null;
        });
    };
    ReportsView.prototype.ExecuteParamters = function (reportDetails, e) {
        if (e === void 0) { e = null; }
        var that = this;
        if (!this.disableClick && e.event && e.event.currentTarget) {
            e.event.preventDefault();
            e.event.stopPropagation();
            return;
        }
        this.disableClick = false;
        var clear = setTimeout(function () {
            that.disableClick = true;
            clearInterval(clear);
        }, 3000);
        this.Parameters = new ParametersView("#reportsParamtersPopup", reportDetails, ParametersPopupType.InMemory);
        this.Parameters.GetParameters();
        this.Parameters.GetPopup().option("hiding", function () {
            that.Parameters = null;
        });
    };
    ReportsView.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.queueCmdDx = $("#queueCmdDx").dxButton("instance");
        this.rolesOnDx = $("#rolesOnDx").dxSwitch("instance");
        this.reportGrid = $("#reportsGridDx").dxDataGrid("instance");
        if (this.IsDefined(this.detailCmdDx)) {
            this.detailCmdDx.option().onClick = function (e) {
                that.Loading().show();
                var key = that.reportGrid.option('focusedRowKey');
                that.reportGrid.byKey(key).done(function (e) {
                    var reportDetails = new ReportViewModel();
                    reportDetails.ConnectionId = e.ConnectionId;
                    reportDetails.Name = e.Name;
                    reportDetails.ViewId = e.ViewId;
                    reportDetails.RoleId = null;
                    reportDetails.Type = "Detail Grid";
                    that.ExecuteParamters(reportDetails);
                });
            };
        }
        if (this.IsDefined(this.sumaryCmdDx)) {
            this.sumaryCmdDx.option().onClick = function (e) {
                that.Loading().show();
                var key = that.reportGrid.option('focusedRowKey');
                that.reportGrid.byKey(key).done(function (e) {
                    var reportDetails = new ReportViewModel();
                    reportDetails.ConnectionId = e.ConnectionId;
                    reportDetails.Name = e.Name;
                    reportDetails.ViewId = e.ViewId;
                    reportDetails.RoleId = null;
                    reportDetails.Type = "Summary Grid";
                    that.ExecuteParamters(reportDetails);
                });
            };
        }
        if (this.IsDefined(this.finishCmdDx)) {
            this.finishCmdDx.option().onClick = function (e) {
                that.Loading().show();
                var key = that.reportGrid.option('focusedRowKey');
                that.reportGrid.byKey(key).done(function (e) {
                    var reportDetails = new ReportViewModel();
                    reportDetails.ConnectionId = e.ConnectionId;
                    reportDetails.Name = e.Name;
                    reportDetails.ViewId = e.ViewId;
                    reportDetails.RoleId = null;
                    reportDetails.Type = "Finished Report";
                    that.ExecuteParamters(reportDetails);
                });
            };
        }
        if (this.IsDefined(this.vizCmdDx)) {
            this.vizCmdDx.option().onClick = function (e) {
                that.Loading().show();
                var key = that.reportGrid.option('focusedRowKey');
                that.reportGrid.byKey(key).done(function (e) {
                    var reportDetails = new ReportViewModel();
                    reportDetails.ConnectionId = e.ConnectionId;
                    reportDetails.Name = e.Name;
                    reportDetails.ViewId = e.ViewId;
                    reportDetails.RoleId = null;
                    reportDetails.Type = "Visualize";
                    that.ExecuteParamters(reportDetails);
                });
            };
        }
        if (this.IsDefined(this.downloadCmdDx)) {
            this.downloadCmdDx.option().onClick = function (e) {
                that.Loading().show();
                var key = that.reportGrid.option('focusedRowKey');
                that.reportGrid.byKey(key).done(function (e) {
                    var reportDetails = new ReportViewModel();
                    reportDetails.ConnectionId = e.ConnectionId;
                    reportDetails.Name = e.Name;
                    reportDetails.ViewId = e.ViewId;
                    reportDetails.RoleId = that.GetRoleId(e);
                    reportDetails.Type = "Finished Report";
                    that.DownloadParamters(reportDetails);
                });
            };
        }
        if (this.IsDefined(this.queueCmdDx)) {
            this.queueCmdDx.option().onClick = function (e) {
                that.Loading().show();
                var key = that.reportGrid.option('focusedRowKey');
                that.reportGrid.byKey(key).done(function (e) {
                    var reportDetails = new ReportViewModel();
                    reportDetails.ConnectionId = e.ConnectionId;
                    reportDetails.Name = e.Name;
                    reportDetails.ViewId = e.ViewId;
                    reportDetails.RoleId = that.GetRoleId(e);
                    reportDetails.Type = "";
                    that.QueueParamters(reportDetails);
                });
            };
        }
        if (this.IsDefined(this.reportGrid)) {
            this.reportGrid.option().onOptionChanged = function (e) {
                if (e.fullName === "focusedRowKey") {
                    if (e.value && e.value.ViewId) {
                        that.CheckReportExecutionRights(e.value.ViewId);
                    }
                    else {
                        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);
                        if (that.IsDefined(that.queueCmdDx)) {
                            that.queueCmdDx.option('disabled', true);
                        }
                        if (that.IsDefined(that.rolesOnDx)) {
                            that.rolesOnDx.option('disabled', true);
                        }
                    }
                }
            };
        }
        if (this.IsDefined(this.rolesOnDx)) {
            this.rolesOnDx.option().onValueChanged = function (e) {
                that.reportGrid.refresh().done(function () {
                    that.reportGrid.columnOption("Role", "visible", e.value);
                });
                if (window.sessionStorage) {
                    sessionStorage.setItem("reportsGridDx_Role", e.value);
                }
                that.downloadCmdDx.option('type', e.value ? 'danger' : 'normal');
                if (that.IsDefined(that.queueCmdDx)) {
                    that.queueCmdDx.option('type', e.value ? 'danger' : 'normal');
                }
            };
            if (window.sessionStorage) {
                var roleValue = sessionStorage.getItem("reportsGridDx_Role");
                if (this.IsNotEmpty(roleValue)) {
                    this.rolesOnDx.option("value", roleValue === "true");
                }
            }
        }
    };
    ReportsView.prototype.GetRoleId = function (row) {
        if (this.IsDefined(this.rolesOnDx)) {
            var withRole = this.rolesOnDx.option('value');
            return withRole ? row.RoleId : null;
        }
        else {
            return null;
        }
    };
    ReportsView.prototype.CheckReportExecutionRights = function (reportId) {
        var that = this;
        if (reportId) {
            this.GetLoadPanelInstance().show();
            var callUrl = this.callController + '/CheckReportExecutionRights';
            var data = {
                __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
                reportId: reportId,
            };
            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);
                        that.sumaryCmdDx.option('disabled', !d.Summary);
                        that.finishCmdDx.option('disabled', !d.Finished);
                        that.vizCmdDx.option('disabled', !d.Visualize);
                        that.downloadCmdDx.option('disabled', !d.Finished);
                        if (that.IsDefined(that.queueCmdDx)) {
                            that.queueCmdDx.option('disabled', !(d.Details || d.Summary || d.Finished || d.Visualize));
                        }
                        if (that.IsDefined(that.rolesOnDx)) {
                            that.rolesOnDx.option('disabled', !(d.Details || d.Summary || d.Finished || d.Visualize));
                        }
                        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);
                    if (that.IsDefined(that.queueCmdDx)) {
                        that.queueCmdDx.option('disabled', true);
                    }
                    if (that.IsDefined(that.rolesOnDx)) {
                        that.rolesOnDx.option('disabled', true);
                    }
                    that.GetLoadPanelInstance().hide();
                },
                errorMsg: "Error occurs during operation",
            });
            this.ajaxService.send(callOptions);
        }
    };
    ReportsView.prototype.GetLoadPanelInstance = function () {
        return $("#loadingDx").dxLoadPanel("instance");
    };
    return ReportsView;
}(BaseView));
var View = window.View || {};
document.addEventListener("DOMContentLoaded", function documentReady() {
    this.removeEventListener("DOMContentLoaded", documentReady);
    View = window.View = new ReportsView();
});
