/******************************************************************************
This class is responsible for all aspects of managing the Data Series Settings
dialog.

*****************************************************************************/
var Dashboards;
(function (Dashboards) {
    var SetupControl;
    (function (SetupControl) {
        var DataSeriesEditDialog = (function () {
            function DataSeriesEditDialog(seriesOptions, allSetupItems, okCallback, editedSeries) {
                if (okCallback === void 0) { okCallback = Core.CallBackPayload.None; }
                // State variables
                this.maxSeriesTitleLength = 80;
                this.colorPickerOpen = false;
                this.seriesMeasurementSelection = null;
                this.seriesSourceSelection = null;
                this.okWasClicked = false;
                this.allSetupItems = [];
                this.allSetupItems = allSetupItems;
                this.seriesOptions = seriesOptions;
                this.okCallback = okCallback;
                // Clone it
                var clonedSeries = JSON.parse(JSON.stringify(editedSeries));
                this.currentSeriesOption = new SetupControl.DataSeries.SeriesOption(clonedSeries.setting);
            }
            DataSeriesEditDialog.ShowDialog = function (seriesOptions, allSetupItems, okCallback, editedSeries) {
                var dialog = new DataSeriesEditDialog(seriesOptions, allSetupItems, okCallback, editedSeries);
                dialog.showDialog();
            };
            DataSeriesEditDialog.prototype.showDialog = function () {
                var _this = this;
                var templateOptions = {
                    model: {
                        sysDataServiceRoot: fwk.url.get("RootService")
                    }
                };
                TemplateUtil.LocAndLoad(DataSeriesEditDialog.SetupControlDialogTemplateUri, new Core.CallBack(function (template) {
                    _this.$dialog = $(template);
                    _this.renderDialog();
                }), templateOptions);
            };
            // Called after the Template has been loaded
            DataSeriesEditDialog.prototype.renderDialog = function () {
                var _this = this;
                this.bindEventHandlers();
                this.isNew = !this.currentSeriesOption || !this.currentSeriesOption.SourceId;
                // Set initial State
                this.clearValidation();
                var title;
                if (this.isNew) {
                    // Set dialog title
                    title = i18n.loc.unencoded('Gadgets', 'DataSeriesControl_AddDataSeriesTitle');
                    $.extend(this.currentSeriesOption, this.getDefaultSeriesOptions());
                }
                else {
                    // Set dialog title
                    title = i18n.loc.unencoded('Gadgets', 'DataSeriesControl_EditDataSeriesTitle');
                }
                this.$dialog.dialog({
                    modal: true,
                    width: 850,
                    height: this.isSmallRenderWindow() ? 500 : 600,
                    title: title,
                    autoResize: false,
                    resizable: false,
                    closeText: i18n.loc.s('General', 'Close'),
                    buttons: [],
                    open: function () {
                        // Setup non-standard UI controls
                        _this.initializeDialogComplexControls();
                        // Populate Series dialog with current series
                        _this.populateDataSeriesControl();
                    },
                    beforeClose: function (event, ui) {
                        // Callback with current options
                        if (_this.okWasClicked) {
                            if (!_this.isValid()) {
                                _this.okWasClicked = false;
                                return false;
                            }
                            _this.okCallback.call(_this.okWasClicked, _this.currentSeriesOption);
                        }
                        // Move SMP Selectors back to template
                        _this.seriesColorPicker.destroy();
                        Controls.Smp.SmpSelector.SingleSourceSelector().detachSourceSelectorFromContainer();
                        Controls.Smp.SmpSelector.SingleMeasurementSelector().detachMeasurementSelectorFromContainer();
                        return true;
                    },
                    close: function (event, ui) {
                        _this.$dialog.remove();
                    }
                });
            };
            DataSeriesEditDialog.prototype.isSmallRenderWindow = function () {
                return $('#mainContent').height() < 600;
            };
            // Bind all static event handlers.  Should only ever be called once.
            DataSeriesEditDialog.prototype.bindEventHandlers = function () {
                var _this = this;
                this.$dialog.find('.dialog-okbutton').click(function () {
                    _this.okWasClicked = true;
                    _this.$dialog.dialog('close');
                });
                this.$dialog.find('.CancelLink').click(function () {
                    _this.okWasClicked = false;
                    _this.$dialog.dialog('close');
                });
                // Data Series Title change
                this.$dialog.find('.seriesOptionTitleTypeCustom').click(function () {
                    _this.updateSeriesAutoTitle();
                });
                // Data Series Unit change
                this.$dialog.find('.seriesOptionUnitTypeCustom').click(function () {
                    _this.updateSeriesAutoUnits();
                });
                Core.KeyboardEvent.RegisterKeyboardEvent(this.$dialog, Core.Keys.Enter, this.CanHandleKeyPress, new Core.CallBack(function () {
                    _this.$dialog.find('.dialog-okbutton').click();
                }));
            };
            DataSeriesEditDialog.prototype.CanHandleKeyPress = function (e) {
                var $target = $(e.target);
                if ($target.hasClass('searchField')) {
                    return false;
                }
                // If the focused element is not a button then yeah go ahead and handle the key press
                if ($target.is('button') || ($target.prop('type') == 'button')) {
                    return false;
                }
                return true;
            };
            // There is an issue where the color pickers must be initialized AFTER the dialog exists
            // and is loaded.  We set them up, and then can reuse them.
            DataSeriesEditDialog.prototype.initializeDialogComplexControls = function () {
                // Create call backs to ensure we maintain scope in the callback.
                var _this = this;
                // If this is the first time loading, we setup the msDropdown (line thickness image dropdown).
                // First set up the Thickness drop down.  We need to track when it is open, so we can force it closed on blur or other cases.
                this.$dialog.find('.seriesOptionLineWidth').blur(function () {
                    _this.$dialog.find('.seriesOptionLineWidth').msDropDown().data('dd').close();
                });
                this.$dialog.find('.seriesOptionLineWidth').msDropDown({ openDirection: 'alwaysUp' });
                this.$dialog.find('.seriesOptionLineWidth').msDropDown().data('dd').on('mouseup', function () {
                    _this.linePickerShown();
                });
                // Get the id of the ms Dropdown
                var msId = this.$dialog.find('.seriesOptionLineWidth').msDropDown().prop('id');
                // Set the width of the drop down
                $("#" + msId + "_msdd").css('width', '60px'); // Hide the autocomplete input
                $("#" + msId + "_titleText").addClass('hidden');
                // Use standard down arrow instead of image
                this.$dialog.find('.ddArrow').html('▼');
                // Color pickers need to be re-instantiated each load to ensure they work correctly.
                var seriesColorPickerOptions = {
                    $container: this.$dialog.find('.seriesOptionColorSelect'),
                    color: this.currentSeriesOption.color,
                    palette: Dashboards.Views.Application.DataSeriesSpectrum,
                    localStorageKey: "DataSeries"
                };
                this.seriesColorPicker = new Controls.ColorPicker.ColorPickerControl(seriesColorPickerOptions, new Core.CallBack(function () { }));
                if (this.isSmallRenderWindow()) {
                    this.$dialog.find('.dataSeriesOptionDeviceSection, .dataSeriesOptionTopicSection').addClass('dataSeriesOptionSectionSmall');
                }
            };
            DataSeriesEditDialog.prototype.getDefaultSeriesOptions = function () {
                // If we have a previous source selection, default to that.
                return {
                    SourceId: DataSeriesEditDialog.LastSelectSource ? DataSeriesEditDialog.LastSelectSource.DeviceId : null,
                    MeasurementId: DataSeriesEditDialog.LastSelectMeasurement ? DataSeriesEditDialog.LastSelectMeasurement.TopicId : null,
                    lineWidth: 3,
                    color: this.getNextUnusedColor()
                };
            };
            /************************ Settings Management ****************************/
            // Perform validation and save the series from UI settings.
            // - If validation fails, then the dialog will not close and return false
            // - Else it will close and update the seriesOptions with the updated series settings.
            DataSeriesEditDialog.prototype.isValid = function () {
                var _this = this;
                var validationMsg;
                ///****************  Reset Validation and start validating
                this.clearValidation();
                /* Series settings */
                var seriesDiv = this.$dialog;
                // Set the id
                this.currentSeriesOption.uniqueId = seriesDiv.find('.optionUniqueId').val();
                // Validate Source Selection
                if (!this.seriesSourceSelection || !this.seriesSourceSelection.DeviceId) {
                    seriesDiv.find('.sourceTreeWrapper').addClass('validationError');
                    validationMsg = validationMsg || i18n.loc.s('SourceMeasurementSelector', 'Validation_SelectDevice');
                }
                // Validate Measurement Selection
                if (!this.seriesMeasurementSelection || this.seriesMeasurementSelection.TopicId == 0) {
                    seriesDiv.find('.measurementTreeWrapper').addClass('validationError');
                    validationMsg = validationMsg || i18n.loc.s('SourceMeasurementSelector', 'Validation_SelectTopic');
                }
                // Series Title
                var $seriesOptionTitle;
                if (!validationMsg) {
                    // Check for a valid title
                    $seriesOptionTitle = seriesDiv.find('.seriesOptionTitle');
                    var result = Validation.Text.validateUserText($seriesOptionTitle, {
                        // custom text validation
                        custom: function (text) { return !(seriesDiv.find('.seriesOptionTitleTypeCustom').prop('checked') && text.length === 0); },
                        customMessage: i18n.loc.s('Gadgets', 'DataSeriesControl_Validation_DataSeriesTitle')
                    });
                    if (!result.valid) {
                        $seriesOptionTitle.addClass('validationError');
                        validationMsg = result.message;
                    }
                }
                // Display Units
                var $seriesDisplayUnits;
                if (!validationMsg) {
                    $seriesDisplayUnits = seriesDiv.find('.seriesOptionUnits');
                    var result = Validation.Text.validateUserText($seriesDisplayUnits, { allowEmpty: true });
                    if (!result.valid) {
                        $seriesDisplayUnits.addClass('validationError');
                        validationMsg = result.message;
                    }
                }
                if (!validationMsg) {
                    // Test for unique Series Names
                    // Title
                    var currentTitle = $seriesOptionTitle.val().trim();
                    if (currentTitle.length > this.maxSeriesTitleLength) {
                        currentTitle = currentTitle.substring(0, this.maxSeriesTitleLength - 1);
                    }
                    _.each(this.seriesOptions, function (existingSeries, idx) {
                        if (existingSeries.uniqueId != _this.currentSeriesOption.uniqueId &&
                            currentTitle == existingSeries.title) {
                            seriesDiv.find(".seriesOptionTitle").addClass('validationError');
                            validationMsg = validationMsg || i18n.loc.s('Gadgets', 'DataSeriesControl_Validation_DuplicateName');
                            return true;
                        }
                    });
                }
                // Multiplier
                if (!validationMsg) {
                    var multiplier = seriesDiv.find(".seriesOptionMultiplier").val();
                    multiplier = NumberUtil.parseUserInput(multiplier, '');
                    if (multiplier === '') {
                        seriesDiv.find(".seriesOptionMultiplier").addClass('validationError');
                        validationMsg = i18n.loc.s('General', 'ValidationWarning_InvalidDecimal');
                    }
                }
                if (validationMsg) {
                    validationMsg = validationMsg || i18n.loc.s('General', 'Validation_Failed');
                    seriesDiv.find('.dialogValidationErrorMessage').html(validationMsg);
                    seriesDiv.find('.validationError').first().focus();
                    return false;
                }
                ///****************  Now save data
                function setValue(obj, prop, val) {
                    if (!_.isUndefined(val)) {
                        obj[prop] = val;
                    }
                    else {
                        delete obj[prop];
                    }
                }
                this.currentSeriesOption.SourceId = this.seriesSourceSelection.DeviceId;
                this.currentSeriesOption.DeviceName = this.seriesSourceSelection.Name;
                this.currentSeriesOption.MeasurementId = this.seriesMeasurementSelection.TopicId.toString();
                this.currentSeriesOption.TopicName = this.seriesMeasurementSelection.TopicName;
                // Title
                setValue(this.currentSeriesOption, 'customTitle', seriesDiv.find('.seriesOptionTitleTypeCustom').prop('checked'));
                this.currentSeriesOption.title = $seriesOptionTitle.val();
                if (this.currentSeriesOption.title.length > this.maxSeriesTitleLength) {
                    this.currentSeriesOption.title = this.currentSeriesOption.title.substring(0, this.maxSeriesTitleLength - 1);
                }
                // Units
                setValue(this.currentSeriesOption, 'customUnits', seriesDiv.find('.seriesOptionUnitTypeCustom').prop('checked'));
                this.currentSeriesOption.units = seriesDiv.find('.seriesOptionUnits').val();
                if (this.currentSeriesOption.units) {
                    this.currentSeriesOption.units = this.currentSeriesOption.units.trim();
                }
                //editSeries.numberOfDecimals = seriesDiv.find('.seriesOptionNumberOfDecimals option:selected').val();
                this.currentSeriesOption.lineWidth = parseInt(seriesDiv.find('.seriesOptionLineWidth').msDropDown().data('dd').get("value"));
                this.currentSeriesOption.color = this.seriesColorPicker.getColor();
                this.currentSeriesOption.axis = seriesDiv.find('.seriesOptionAxis').val();
                this.currentSeriesOption.seriesType = seriesDiv.find('.seriesOptionSeriesDisplayType').val();
                // Multiplier
                this.currentSeriesOption.multiplier = Number(multiplier);
                // If this is new, we add it to the options series list.
                if (this.isNew) {
                    this.seriesOptions.push(this.currentSeriesOption);
                }
                return true;
            };
            /************************ State Management *******************************/
            DataSeriesEditDialog.prototype.getNextUnusedColor = function () {
                var unusedColors = fwk.palettes['DataSeries'].slice();
                // Find an appropriate next unused default color
                _.each(this.seriesOptions, function (optionsOfASeries, idx) {
                    var matchIdx = unusedColors.indexOf(optionsOfASeries.color);
                    if (matchIdx >= 0)
                        unusedColors.splice(matchIdx, 1);
                });
                // Set new color, else just recycle colors
                if (unusedColors.length > 0)
                    return unusedColors[0];
                else {
                    return fwk.palettes['DataSeries'][this.seriesOptions.length % fwk.palettes['DataSeries'].length];
                }
            };
            DataSeriesEditDialog.prototype.clearValidation = function () {
                // Reset Validation on Data Series Setup
                this.$dialog.find('.dialogValidationErrorMessage').html('');
                this.$dialog.find('.validationError').removeClass('validationError');
            };
            DataSeriesEditDialog.prototype.colorPickerShown = function () {
                this.$dialog.find('.seriesOptionLineWidth').msDropDown().data('dd').close();
                this.colorPickerOpen = true;
            };
            DataSeriesEditDialog.prototype.linePickerShown = function () {
                if (this.colorPickerOpen) {
                }
            };
            DataSeriesEditDialog.prototype.colorPickerHidden = function () {
                this.colorPickerOpen = false;
            };
            DataSeriesEditDialog.prototype.updateSeriesAutoTitle = function () {
                // Build the Series title if in auto mode based on selection
                if (this.$dialog.find('.seriesOptionTitleTypeCustom').prop('checked')) {
                    this.$dialog.find('.seriesOptionTitle').prop('disabled', '');
                }
                else {
                    this.$dialog.find('.seriesOptionTitle').prop('disabled', 'disabled');
                    var deviceTitle = '';
                    if (this.seriesSourceSelection) {
                        deviceTitle = this.seriesSourceSelection.Name;
                        // If there is no grouping, then we need to add group to name
                        if (this.seriesSourceSelection.GroupName) {
                            deviceTitle = this.seriesSourceSelection.GroupName + '.' + deviceTitle;
                        }
                    }
                    var topicTitle = '';
                    if (this.seriesMeasurementSelection) {
                        topicTitle = this.seriesMeasurementSelection.TopicName;
                    }
                    var title = StringUtil.format('{0} {1}', deviceTitle, topicTitle);
                    this.clearValidation();
                    this.$dialog.find('.seriesOptionTitle').val(title);
                }
            };
            DataSeriesEditDialog.prototype.updateSeriesAutoUnits = function () {
                // Build the Series Units if in auto mode based on selection
                if (this.$dialog.find('.seriesOptionUnitTypeCustom').prop('checked')) {
                    this.$dialog.find('.seriesOptionUnits').prop('disabled', '');
                }
                else {
                    this.$dialog.find('.seriesOptionUnits').prop('disabled', 'disabled');
                    var units = '';
                    if (this.seriesMeasurementSelection) {
                        units = this.seriesMeasurementSelection.UnitName;
                    }
                    this.clearValidation();
                    this.$dialog.find('.seriesOptionUnits').val(units);
                }
            };
            /************************ End State Management ***************************/
            /************************ Data Series Management *************************/
            // Populates the Series dialog from a series
            DataSeriesEditDialog.prototype.populateDataSeriesControl = function () {
                var seriesDiv = this.$dialog.find('.dataSeriesOptionContent');
                // Set the Id, or create a new one.
                seriesDiv.find('.optionUniqueId').val(this.currentSeriesOption.uniqueId || Guid.newGuid());
                // Title
                seriesDiv.find('.seriesOptionTitle').val(this.currentSeriesOption.title);
                if (this.currentSeriesOption.customTitle === true) {
                    seriesDiv.find('.seriesOptionTitleTypeCustom').prop('checked', 'checked');
                    seriesDiv.find('.seriesOptionTitle').prop('disabled', '');
                }
                else {
                    seriesDiv.find('.seriesOptionTitleTypeCustom').prop('checked', false);
                    seriesDiv.find('.seriesOptionTitle').prop('disabled', 'disabled');
                }
                // Units
                seriesDiv.find('.seriesOptionUnits').val(this.currentSeriesOption.units);
                if (this.currentSeriesOption.customUnits === true) {
                    seriesDiv.find('.seriesOptionUnitTypeCustom').prop('checked', 'checked');
                    seriesDiv.find('.seriesOptionUnits').prop('disabled', '');
                }
                else {
                    seriesDiv.find('.seriesOptionUnits').prop('disabled', 'disabled');
                    seriesDiv.find('.seriesOptionUnitTypeCustom').prop('checked', false);
                }
                this.smpInformationLoading();
                Controls.Smp.SmpSelector.LoadLinkedSelector(new Core.CallBackSuccess(this.smpInformationLoaded, this), {
                    $sourceContainer: this.$dialog.find('.dataSeriesOptionDeviceSection'),
                    sourceSelectedCallback: new Core.CallBackPayload(this.sourceSelectionChange, this),
                    selectedSource: this.currentSeriesOption.SourceId,
                    treeHeight: this.isSmallRenderWindow() ? 120 : 220,
                }, {
                    $measurementContainer: this.$dialog.find('.dataSeriesOptionTopicSection'),
                    measurementSelectedCallback: new Core.CallBackPayload(this.measurementSelectionChange, this),
                    selectedMeasurement: this.currentSeriesOption.MeasurementId,
                    treeHeight: this.isSmallRenderWindow() ? 120 : 220,
                    sourceDataLogFilterValue: true
                });
                // General settings
                // We must reach into the entire set of settings, to look for Axis settings.
                var allSettings = new Settings.SettingHandler(this.allSetupItems);
                var leftAxisType = allSettings.byName(Settings.Gadget.LeftAxisType.name);
                if (!leftAxisType || leftAxisType === 'none') {
                    // this gadget does NOT have an Axis settings... hide them...
                    seriesDiv.find('.axisRelatedSetting').hide();
                }
                else {
                    // gadget supports Left axis.  Show Series type selector.
                    seriesDiv.find('.seriesOptionSeriesDisplayType').val(this.currentSeriesOption.seriesType);
                    var rightAxisType = allSettings.byName(Settings.Gadget.RightAxisType.name);
                    if (!rightAxisType || rightAxisType === 'none') {
                        // This gadget does NOT support multiple axes.  Remove the right axis choice.
                        $('.seriesOptionAxis option[value="right"]').remove();
                    }
                    else {
                        seriesDiv.find('.seriesOptionAxis').val(this.currentSeriesOption.axis);
                    }
                }
                seriesDiv.find('.seriesOptionLineWidth').msDropDown().data('dd').set("value", this.currentSeriesOption.lineWidth);
                if (_.isNull(this.currentSeriesOption.multiplier) || _.isUndefined(this.currentSeriesOption.multiplier)) {
                    seriesDiv.find(".seriesOptionMultiplier").val('1');
                }
                else {
                    seriesDiv.find(".seriesOptionMultiplier").val(i18n.formatNumber(this.currentSeriesOption.multiplier));
                }
            };
            // A call back from the SmpSelector, triggered when a measurement selection changes
            DataSeriesEditDialog.prototype.measurementSelectionChange = function (valid, topic) {
                if (this.$dialog && topic) {
                    DataSeriesEditDialog.LastSelectMeasurement = topic;
                    this.seriesMeasurementSelection = topic;
                    this.updateSeriesAutoTitle();
                    this.updateSeriesAutoUnits();
                }
            };
            // A call back from the SmpSelector, triggered when a source selection changes
            DataSeriesEditDialog.prototype.sourceSelectionChange = function (valid, device) {
                if (this.$dialog && device) {
                    DataSeriesEditDialog.LastSelectSource = device;
                    this.seriesSourceSelection = device;
                    this.updateSeriesAutoTitle();
                }
            };
            // Blocks while loading
            DataSeriesEditDialog.prototype.smpInformationLoading = function () {
                if (this.$dialog) {
                    this.$dialog.find('.dataSeriesOptionContent').block({
                        message: i18n.loc.s('SourceMeasurementSelector', 'LoadingSourceMeasurements')
                    });
                }
            };
            // A call back from the SmpSelector, triggered when the Smp Info is loaded
            DataSeriesEditDialog.prototype.smpInformationLoaded = function () {
                if (this.$dialog) {
                    this.$dialog.find('.dataSeriesOptionContent').unblock();
                    this.$dialog.find('.dialog-okbutton').prop('disabled', false);
                }
            };
            DataSeriesEditDialog.SetupControlDialogTemplateUri = 'Content/Gadgets/_baseSetupControls/DataSeriesSetupControlDialogTemplate.html';
            // Convenience variables to preselect last SMP on new
            DataSeriesEditDialog.LastSelectSource = null;
            DataSeriesEditDialog.LastSelectMeasurement = null;
            return DataSeriesEditDialog;
        }());
        SetupControl.DataSeriesEditDialog = DataSeriesEditDialog;
    })(SetupControl = Dashboards.SetupControl || (Dashboards.SetupControl = {}));
})(Dashboards || (Dashboards = {}));
//# sourceMappingURL=DataSeriesSetupControlDialog.js.map