/******************************************************************************
This class is responsible for all aspects of managing the Data Series Settings
dialog.
*****************************************************************************/
var Dashboards;
(function (Dashboards) {
    var SetupControl;
    (function (SetupControl) {
        var EnergyEquivalencyDataSeriesEditDialog = (function () {
            function EnergyEquivalencyDataSeriesEditDialog(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.EnergyEquivalencyDataSeries.SeriesOption(clonedSeries.setting);
            }
            EnergyEquivalencyDataSeriesEditDialog.ShowDialog = function (seriesOptions, allSetupItems, okCallback, editedSeries) {
                var dialog = new EnergyEquivalencyDataSeriesEditDialog(seriesOptions, allSetupItems, okCallback, editedSeries);
                dialog.showDialog();
            };
            EnergyEquivalencyDataSeriesEditDialog.prototype.showDialog = function () {
                var _this = this;
                var templateOptions = {
                    model: {
                        sysDataServiceRoot: fwk.url.get("RootService")
                    }
                };
                TemplateUtil.LocAndLoad(EnergyEquivalencyDataSeriesEditDialog.SetupControlDialogTemplateUri, new Core.CallBack(function (template) {
                    _this.$dialog = $(template);
                    _this.renderDialog();
                }), templateOptions);
            };
            // Called after the Template has been loaded
            EnergyEquivalencyDataSeriesEditDialog.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.s('Gadgets', 'DataSeriesControl_AddDataSeriesTitle');
                    $.extend(this.currentSeriesOption, this.getDefaultSeriesOptions());
                }
                else {
                    // Set dialog title
                    title = i18n.loc.s('Gadgets', 'DataSeriesControl_EditDataSeriesTitle');
                }
                this.$dialog.dialog({
                    modal: true,
                    width: 850,
                    height: this.isSmallRenderWindow() ? 490 : 530,
                    title: title,
                    autoResize: false,
                    resizable: false,
                    closeText: i18n.loc.s('General', 'Close'),
                    buttons: [],
                    open: function () {
                        // 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
                        if (_this.$dialog.find('.dataSeriesOptionDeviceSection #sourceSelector').length > 0) {
                            $('#templates').append(_this.$dialog.find('.dataSeriesOptionDeviceSection #sourceSelector').detach());
                        }
                        if (_this.$dialog.find('.dataSeriesOptionTopicSection #measurementSelector').length > 0) {
                            $('#templates').append(_this.$dialog.find('.dataSeriesOptionTopicSection #measurementSelector').detach());
                        }
                        return true;
                    },
                    close: function (event, ui) {
                        _this.$dialog.remove();
                    }
                });
            };
            EnergyEquivalencyDataSeriesEditDialog.prototype.isSmallRenderWindow = function () {
                return $('#mainContent').height() < 600;
            };
            // Bind all static event handlers.  Should only ever be called once.
            EnergyEquivalencyDataSeriesEditDialog.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');
                });
                Core.KeyboardEvent.RegisterKeyboardEvent(this.$dialog, Core.Keys.Enter, this.CanHandleKeyPress, new Core.CallBack(function () {
                    _this.$dialog.find('.dialog-okbutton').click();
                }));
            };
            EnergyEquivalencyDataSeriesEditDialog.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;
            };
            EnergyEquivalencyDataSeriesEditDialog.prototype.getDefaultSeriesOptions = function () {
                // If we have a previous source selection, default to that.
                return {
                    SourceId: EnergyEquivalencyDataSeriesEditDialog.LastSelectSource ? EnergyEquivalencyDataSeriesEditDialog.LastSelectSource.DeviceId : null,
                    MeasurementId: EnergyEquivalencyDataSeriesEditDialog.LastSelectMeasurement ? EnergyEquivalencyDataSeriesEditDialog.LastSelectMeasurement.TopicId : null
                };
            };
            /************************ 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.
            EnergyEquivalencyDataSeriesEditDialog.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');
                }
                var $seriesOptionTitle;
                if (!validationMsg) {
                    // Not sure this is here - it doesn't seem to be user editable
                    $seriesOptionTitle = seriesDiv.find('.seriesOptionTitle');
                    $seriesOptionTitle.val($seriesOptionTitle.val().trim());
                }
                if (!validationMsg) {
                    // Test for unique Series Names
                    // Title
                    var currentTitle = $seriesOptionTitle.val().trim();
                    _.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
                var multiplier = seriesDiv.find(".seriesOptionMultiplier").val();
                if (!validationMsg) {
                    multiplier = NumberUtil.parseUserInput(multiplier, '');
                    if (multiplier === '') {
                        seriesDiv.find(".seriesOptionMultiplier").addClass('validationError');
                        validationMsg = validationMsg || i18n.loc.s('EnergyGadgets', 'DataSeries_InvalidMultiplier');
                    }
                }
                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
                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
                this.currentSeriesOption.title = $seriesOptionTitle.val();
                if (this.currentSeriesOption.title.length > this.maxSeriesTitleLength) {
                    this.currentSeriesOption.title = this.currentSeriesOption.title.substring(0, this.maxSeriesTitleLength - 1);
                }
                // Units
                this.currentSeriesOption.units = seriesDiv.find('.seriesOptionUnits').val();
                if (this.currentSeriesOption.units) {
                    this.currentSeriesOption.units = this.currentSeriesOption.units.trim();
                }
                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 *******************************/
            EnergyEquivalencyDataSeriesEditDialog.prototype.clearValidation = function () {
                // Reset Validation on Data Series Setup
                this.$dialog.find('.dialogValidationErrorMessage').html('');
                this.$dialog.find('.validationError').removeClass('validationError');
            };
            EnergyEquivalencyDataSeriesEditDialog.prototype.updateAutoMultiplier = function (topic) {
                var formattedMultiplier = '';
                if (topic.UnitSymbol) {
                    var unitSymbol = topic.UnitSymbol.replace('CDM.UnitSymbol.', '');
                    if (unitSymbol) {
                        var handler = new Settings.SettingHandler(this.allSetupItems);
                        var existingMultiplier = handler.byNameIgnoreCase('WhConversion_' + unitSymbol);
                        if (existingMultiplier) {
                            formattedMultiplier = i18n.formatNumber(existingMultiplier);
                        }
                    }
                }
                this.$dialog.find('.seriesOptionMultiplier').val(formattedMultiplier);
            };
            EnergyEquivalencyDataSeriesEditDialog.prototype.updateSeriesAutoTitle = function () {
                // Build the Series title
                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);
            };
            EnergyEquivalencyDataSeriesEditDialog.prototype.updateSeriesAutoUnits = function () {
                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
            EnergyEquivalencyDataSeriesEditDialog.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);
                // Units
                seriesDiv.find('.seriesOptionUnits').val(this.currentSeriesOption.units);
                if (this.isSmallRenderWindow()) {
                    this.$dialog.find('.dataSeriesOptionDeviceSection, .dataSeriesOptionTopicSection').addClass('dataSeriesOptionSectionSmall');
                }
                this.smpInformationLoading();
                Controls.Smp.SmpSelector.LoadLinkedSelector(new Core.CallBackSuccess(this.smpInformationLoaded, this), {
                    sourceSelectedCallback: new Core.CallBackPayload(this.sourceSelectionChange, this),
                    selectedSource: this.currentSeriesOption.SourceId,
                    treeHeight: this.isSmallRenderWindow() ? 120 : 220,
                }, {
                    measurementSelectedCallback: new Core.CallBackPayload(this.measurementSelectionChange, this),
                    selectedMeasurement: this.currentSeriesOption.MeasurementId,
                    treeHeight: this.isSmallRenderWindow() ? 120 : 220,
                });
                // General settings
                if (_.isNull(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
            EnergyEquivalencyDataSeriesEditDialog.prototype.measurementSelectionChange = function (valid, topic) {
                if (this.$dialog && topic) {
                    if (_.isUndefined(this.currentSeriesOption.multiplier) || _.isNull(this.currentSeriesOption.multiplier) ||
                        !this.currentSeriesOption.MeasurementId ||
                        this.currentSeriesOption.MeasurementId != topic.TopicId.toString()) {
                        // New topic selection, override the Multiplier
                        this.updateAutoMultiplier(topic);
                    }
                    EnergyEquivalencyDataSeriesEditDialog.LastSelectMeasurement = topic;
                    this.seriesMeasurementSelection = topic;
                    this.updateSeriesAutoTitle();
                    this.updateSeriesAutoUnits();
                }
            };
            // A call back from the SmpSelector, triggered when a source selection changes
            EnergyEquivalencyDataSeriesEditDialog.prototype.sourceSelectionChange = function (valid, device) {
                if (this.$dialog && device) {
                    EnergyEquivalencyDataSeriesEditDialog.LastSelectSource = device;
                    this.seriesSourceSelection = device;
                    this.updateSeriesAutoTitle();
                }
            };
            // Blocks while loading
            EnergyEquivalencyDataSeriesEditDialog.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
            EnergyEquivalencyDataSeriesEditDialog.prototype.smpInformationLoaded = function () {
                if (this.$dialog) {
                    this.$dialog.find('.dataSeriesOptionDeviceSection').append($('#templates #sourceSelector').detach());
                    this.$dialog.find('.dataSeriesOptionTopicSection').append($('#templates #measurementSelector').detach());
                    this.$dialog.find('.dataSeriesOptionContent').unblock();
                    this.$dialog.find('.dialog-okbutton').prop('disabled', false);
                }
            };
            EnergyEquivalencyDataSeriesEditDialog.SetupControlDialogTemplateUri = 'Content/Gadgets/EnergyEquivalency/EnergyEquivalencyDataSeriesSetupControlDialogTemplate.html';
            // Convenience variables to preselect last SMP on new
            EnergyEquivalencyDataSeriesEditDialog.LastSelectSource = null;
            EnergyEquivalencyDataSeriesEditDialog.LastSelectMeasurement = null;
            return EnergyEquivalencyDataSeriesEditDialog;
        }());
        SetupControl.EnergyEquivalencyDataSeriesEditDialog = EnergyEquivalencyDataSeriesEditDialog;
    })(SetupControl = Dashboards.SetupControl || (Dashboards.SetupControl = {}));
})(Dashboards || (Dashboards = {}));
//# sourceMappingURL=EnergyEquivalencyDataSeriesSetupControlDialog.js.map