var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Settings;
(function (Settings) {
    var Gadget;
    (function (Gadget) {
        // Settings.Gadget.SettingGroup.EnergyEquivalencySeries
        Gadget.SettingGroup = $.extend(Gadget.SettingGroup, {
            EnergyEquivalencySeries: "a0a10fbb-7909-4ca9-bbaa-a931011efc3a"
        });
    })(Gadget = Settings.Gadget || (Settings.Gadget = {}));
})(Settings || (Settings = {}));
var Dashboards;
(function (Dashboards) {
    var SetupControl;
    (function (SetupControl) {
        var EnergyEquivalencyDataSeries = (function (_super) {
            __extends(EnergyEquivalencyDataSeries, _super);
            function EnergyEquivalencyDataSeries() {
                _super.call(this, Settings.Gadget.SettingGroup.EnergyEquivalencySeries);
                this.seriesOptions = [];
                this.selectedSeries = null;
                this.$template = $('<div/>');
                this.$dataSeriesTable = null;
                this.$dataSeriesTableEmpty = null;
                this.$rowEntryTemplate = null;
                this.maximumNumberOfSeries = 100;
                this.renderedFirstTime = false;
                this.title = i18n.loc.s('EnergyGadgets', 'MeasurementsTab_Title');
            }
            EnergyEquivalencyDataSeries.CreateInstance = function () {
                var instance = new EnergyEquivalencyDataSeries();
                return instance;
            };
            /* SetupControl Implementation
            ******************************************************************************/
            EnergyEquivalencyDataSeries.prototype.beforeCommit = function () {
                // Need to get the data series ready for saving.
                // Take all the non-data series settings as is.
                var settings = _.filter(this.settings, function (setting) {
                    return !Settings.Gadget.IsDataSeriesSetting(setting);
                });
                // Update internal Ids
                this.updateSeriesOptionIds();
                // Add data series based on the series options we have
                _.each(this.seriesOptions, function (option) {
                    if (option.setting.Value.length > 0) {
                        settings.push(option.setting);
                    }
                    ;
                });
                this.settings = settings;
            };
            ;
            EnergyEquivalencyDataSeries.prototype.draw = function () {
                var _this = this;
                this.$container.empty();
                TemplateUtil.LocAndLoad(EnergyEquivalencyDataSeries.SetupControlTemplateUri, new Core.CallBack(function (template) {
                    _this.$template.html(template);
                    _this.$container.append(_this.$template.find('.dataSeries_SetupControl'));
                    _this.$dataSeriesTable = _this.$container.find('.gadgetOptionDataSeriesTable');
                    _this.$dataSeriesTableEmpty = _this.$container.find('.gadgetOptionDataSeriesTableEmpty');
                    _this.$rowEntryTemplate = _this.$template.find('.energyEquivalencydataSeriesRowEntryTemplate');
                    _this.render();
                }, this));
            };
            EnergyEquivalencyDataSeries.prototype.isConfigured = function () {
                return this.seriesOptions.length > 0;
            };
            EnergyEquivalencyDataSeries.prototype.isManagedSetting = function (name) {
                var managed = false;
                // Pattern-based names
                managed = Settings.Gadget.IsDataSeriesSetting(name);
                return managed;
            };
            EnergyEquivalencyDataSeries.prototype.onFocus = function () {
                var _this = this;
                if (this.renderedFirstTime)
                    return;
                this.renderedFirstTime = true;
                // We must block, as we need the topic utility
                this.$container.find('.dataSeries_SetupControl').block({
                    message: i18n.loc.s('SourceMeasurementSelector', 'LoadingSourceMeasurements')
                });
                var waitHandle = new WaitHandle.PollingHandle({
                    testForComplete: function () {
                        return Controls.Smp.SmpSelector.isDataLoaded();
                    },
                    testIntervalMs: 100,
                    onCompleteCallback: new Core.CallBack(function () {
                        if (!_this.$dataSeriesTable)
                            return;
                        _this.rebuildDataSeriesList();
                        _this.$container.find('.dataSeries_SetupControl').unblock();
                    }, this)
                });
                waitHandle.Start();
            };
            /* Private methods
            ******************************************************************************/
            EnergyEquivalencyDataSeries.prototype.render = function () {
                var _this = this;
                _.each(this.settings, function (setting) {
                    // Convert the old style series names to the new standard PrimaryDataSeries format.
                    if (setting.Name.indexOf('WaterDataSeriesItems') >= 0 ||
                        setting.Name.indexOf('AirDataSeriesItems') >= 0 ||
                        setting.Name.indexOf('GasDataSeriesItems') >= 0 ||
                        setting.Name.indexOf('ElectricityDataSeriesItems') >= 0 ||
                        setting.Name.indexOf('SteamDataSeriesItems') >= 0) {
                        setting.Name = 'PrimaryDataSeries99';
                    }
                    var seriesOption = new EnergyEquivalencyDataSeries.SeriesOption(setting);
                    if (seriesOption.isValid()) {
                        _this.seriesOptions.push(seriesOption);
                    }
                });
                if (this.isSmallRenderWindow()) {
                    this.$dataSeriesTable.addClass('gadgetOptionDataSeriesTableSmall');
                    this.$dataSeriesTableEmpty.addClass('gadgetOptionDataSeriesTableSmallEmpty');
                }
                this.bindEventHandlers();
            };
            // Bind all static event handlers.  Should only ever be called once.
            EnergyEquivalencyDataSeries.prototype.bindEventHandlers = function () {
                var _this = this;
                // Hook up resize handler for Data Series dialog
                // Edit Data Series click 
                this.$container.find('.buttonEditSeries').click(function () {
                    _this.selectedSeries = _this.seriesOptions[_this.$container.find('.gadgetOptionDataSeriesTable .' + Dashboards.Views.Application.ClassCustomListItemSelected).data('seriesoption')];
                    SetupControl.EnergyEquivalencyDataSeriesEditDialog.ShowDialog(_this.seriesOptions, _this.allSettings, new Core.CallBackPayload(_this.seriesDialogClosed, _this), _this.selectedSeries);
                });
                // Delete Data Series Click
                this.$container.find('.buttonRemoveSeries').click(function () {
                    var selSeries = _this.$container.find('.gadgetOptionDataSeriesTable .' + Dashboards.Views.Application.ClassCustomListItemSelected);
                    if (!selSeries || !selSeries[0])
                        return;
                    selSeries = $(selSeries[0]);
                    var selectedIdx = selSeries.data('seriesoption');
                    _this.seriesOptions.splice(selectedIdx, 1); // remove EnergyEquivalencyDataSeries
                    if (_this.seriesOptions[selectedIdx]) {
                        // Select the "next" item, the one that now takes the old place
                        _this.selectedSeries = _this.seriesOptions[selectedIdx];
                    }
                    else if (_this.seriesOptions[selectedIdx - 1]) {
                        // Select the "previous" item, as we deleted the last item
                        _this.selectedSeries = _this.seriesOptions[selectedIdx - 1];
                    }
                    else {
                        // Odd...  Simply reset the selected series so that the first item 
                        // will be selected on the rebuild (if it exists)
                        _this.selectedSeries = null;
                    }
                    _this.rebuildDataSeriesList();
                    _this.setupSeriesListButtonState();
                });
                // Add Data Series Click
                this.$container.find('.buttonAddNewSeries').click(function () {
                    // create a new series option object
                    var newSeries = new EnergyEquivalencyDataSeries.SeriesOption({
                        Name: "PrimaryDataSeries" + (_this.seriesOptions.length + 1),
                        Value: '{"customUnits":false, "customTitle": false}'
                    });
                    SetupControl.EnergyEquivalencyDataSeriesEditDialog.ShowDialog(_this.seriesOptions, _this.allSettings, new Core.CallBackPayload(_this.seriesDialogClosed, _this), newSeries);
                });
            };
            EnergyEquivalencyDataSeries.prototype.seriesDialogClosed = function (valid, updatedSeries) {
                if (valid.success) {
                    var existingIndex = _.findIndex(this.seriesOptions, function (seriesOption) {
                        return seriesOption.uniqueId == updatedSeries.uniqueId;
                    });
                    if (existingIndex < 0) {
                        // add to the local list.
                        this.seriesOptions.push(updatedSeries);
                    }
                    else {
                        this.seriesOptions[existingIndex] = updatedSeries;
                    }
                    // Update the internal Settings
                    updatedSeries.updateSettingsValue();
                    this.selectedSeries = updatedSeries;
                    this.rebuildDataSeriesList();
                }
            };
            EnergyEquivalencyDataSeries.prototype.rebuildDataSeriesList = function () {
                var _this = this;
                this.$dataSeriesTable.empty();
                if (!this.seriesOptions || this.seriesOptions.length == 0) {
                    this.$dataSeriesTable.hide();
                    this.$dataSeriesTableEmpty.show();
                }
                else {
                    this.$dataSeriesTable.show();
                    this.$dataSeriesTableEmpty.hide();
                    // Update internal Ids
                    this.updateSeriesOptionIds();
                    _.each(this.seriesOptions, function (seriesOption, idx) {
                        // Title Cell
                        var seriesDisplay = seriesOption.title;
                        if (seriesOption.units && seriesOption.units.length > 0) {
                            seriesDisplay = seriesDisplay + " (" + seriesOption.units + ")";
                        }
                        var $entryTemplate = _this.$rowEntryTemplate.clone();
                        var topic = Controls.Smp.SmpSelector.getTopic(seriesOption.MeasurementId);
                        var $populatedRowEntry = $(TemplateUtil.ApplyLocalModel('energyEquivalencydataSeriesRowEntry', $entryTemplate.html(), {
                            topicUtility: Controls.Smp.SmpSelector.lookupTopicUtility(topic.UtilityName),
                            title: seriesDisplay
                        }));
                        $populatedRowEntry.data('seriesoption', idx);
                        if (!_this.selectedSeries) {
                            _this.selectedSeries = seriesOption;
                        }
                        if (seriesOption.uniqueId == _this.selectedSeries.uniqueId) {
                            $populatedRowEntry.addClass(Dashboards.Views.Application.ClassCustomListItemSelected);
                        }
                        $populatedRowEntry.click(function () {
                            _this.dataSeriesItemSelect($populatedRowEntry);
                        });
                        $populatedRowEntry.dblclick(function () {
                            var series = _this.seriesOptions[$($populatedRowEntry).data('seriesoption')];
                            SetupControl.EnergyEquivalencyDataSeriesEditDialog.ShowDialog(_this.seriesOptions, _this.allSettings, new Core.CallBackPayload(_this.seriesDialogClosed, _this), series);
                        });
                        _this.$dataSeriesTable.append($populatedRowEntry);
                    });
                    var $selectedEntry = this.$dataSeriesTable.find('.' + Dashboards.Views.Application.ClassCustomListItemSelected);
                    if ($selectedEntry && $selectedEntry.length > 0) {
                        // Ensure selected is visible
                        this.$dataSeriesTable.scrollTop(0);
                        var listTop = this.$dataSeriesTable.position().top;
                        var selectionTop = $selectedEntry.position().top;
                        this.$dataSeriesTable.scrollTop(selectionTop - listTop - 30);
                    }
                }
                this.setupSeriesListButtonState();
            };
            // Clicked on series in Series list
            EnergyEquivalencyDataSeries.prototype.dataSeriesItemSelect = function ($clickedItem) {
                this.$container.find('.gadgetOptionDataSeriesTable .' + Dashboards.Views.Application.ClassCustomListItemSelected).removeClass(Dashboards.Views.Application.ClassCustomListItemSelected);
                $clickedItem.addClass(Dashboards.Views.Application.ClassCustomListItemSelected);
                this.setupSeriesListButtonState();
            };
            EnergyEquivalencyDataSeries.prototype.setupSeriesListButtonState = function () {
                var _this = this;
                if (this.$container.find('.gadgetOptionDataSeriesTable .' + Dashboards.Views.Application.ClassCustomListItemSelected).length < 1) {
                    // No Selection, disable buttons
                    this.$container.find('.buttonRemoveSeries').prop('disabled', 'disabled');
                    this.$container.find('.buttonEditSeries').prop('disabled', 'disabled');
                    this.$container.find('.buttonMoveSeriesUp').addClass(Dashboards.Views.Application.ClassDisabledFakeButton);
                    this.$container.find('.buttonMoveSeriesDown').addClass(Dashboards.Views.Application.ClassDisabledFakeButton);
                }
                else {
                    // Selection
                    this.$container.find('.buttonRemoveSeries').prop('disabled', '');
                    this.$container.find('.buttonEditSeries').prop('disabled', '');
                    this.$container.find('.buttonMoveSeriesUp').addClass(Dashboards.Views.Application.ClassDisabledFakeButton);
                    this.$container.find('.buttonMoveSeriesDown').addClass(Dashboards.Views.Application.ClassDisabledFakeButton);
                    // More than 1 item.  Disable move up/down, then test for valid cases to enable
                    if (this.$container.find('.gadgetOptionDataSeriesTable .' + Dashboards.Views.Application.ClassCustomListItem).length > 1) {
                        _.each(this.$container.find('.gadgetOptionDataSeriesTable .' + Dashboards.Views.Application.ClassCustomListItem), function (row, idx) {
                            if ($(row).hasClass(Dashboards.Views.Application.ClassCustomListItemSelected)) {
                                if (idx > 0) {
                                    // Allow move up
                                    _this.$container.find('.buttonMoveSeriesUp').removeClass(Dashboards.Views.Application.ClassDisabledFakeButton);
                                }
                                if (idx < _this.$container.find('.gadgetOptionDataSeriesTable .' + Dashboards.Views.Application.ClassCustomListItem).length - 1) {
                                    // Allow move down
                                    _this.$container.find('.buttonMoveSeriesDown').removeClass(Dashboards.Views.Application.ClassDisabledFakeButton);
                                }
                            }
                        });
                    }
                }
            };
            EnergyEquivalencyDataSeries.prototype.updateSeriesOptionIds = function () {
                var _this = this;
                var prefixes = ["PrimaryDataSeries"];
                _.each(prefixes, function (prefix) {
                    var number = Number(1);
                    _.each(_this.seriesOptions, function (seriesOption) {
                        if (seriesOption.uniqueId.indexOf(prefix) == 0) {
                            seriesOption.uniqueId = prefix + number;
                            seriesOption.setting.Name = seriesOption.uniqueId;
                            number++;
                        }
                    });
                });
            };
            EnergyEquivalencyDataSeries.SetupControlTemplateUri = 'Content/Gadgets/EnergyEquivalency/EnergyEquivalencyDataSeriesSetupControlTemplate.html';
            return EnergyEquivalencyDataSeries;
        }(Dashboards.Models.SetupControl));
        SetupControl.EnergyEquivalencyDataSeries = EnergyEquivalencyDataSeries;
    })(SetupControl = Dashboards.SetupControl || (Dashboards.SetupControl = {}));
})(Dashboards || (Dashboards = {}));
// Register the Setup Control
Dashboards.Controllers.SetupControl.Register({
    create: Dashboards.SetupControl.EnergyEquivalencyDataSeries.CreateInstance,
    id: Settings.Gadget.SettingGroup.EnergyEquivalencySeries
});
var Dashboards;
(function (Dashboards) {
    var SetupControl;
    (function (SetupControl) {
        var EnergyEquivalencyDataSeries;
        (function (EnergyEquivalencyDataSeries) {
            /// Class that converts a gadget data series setting to/from the options
            // object used by the data series editor dialog.
            var SeriesOption = (function () {
                function SeriesOption(setting) {
                    this.uniqueId = '';
                    this.SourceId = '';
                    this.MeasurementId = '';
                    this.title = '';
                    this.units = '';
                    this.multiplier = null;
                    this.DeviceName = '';
                    this.TopicName = '';
                    if (this.isValidSetting(setting)) {
                        this.setting = setting;
                        this.uniqueId = setting.Name;
                        var value = JSON.parse(setting.Value);
                        this.SourceId = value.DeviceId;
                        this.MeasurementId = value.TopicId;
                        this.title = value.Name;
                        this.multiplier = value.Multiplier;
                        // These aren't fed into the selector; they are present
                        // for quickly showing information about the series 
                        // without incurring a call to the provider service tier.
                        this.DeviceName = value.DeviceName;
                        this.TopicName = value.TopicName;
                    }
                }
                // Indicates if the series option is valid.
                SeriesOption.prototype.isValid = function () {
                    return this.setting !== undefined;
                };
                ;
                SeriesOption.prototype.isValidSetting = function (s) {
                    // Must be a data series and must have a value
                    if (!Settings.Gadget.IsDataSeriesSetting(s))
                        return false;
                    if (!s.Value || s.Value.length <= 0)
                        return false;
                    // Probably a data series setting ....
                    return true;
                };
                // Updates the gadget series setting object with the values
                // set on the option object.
                SeriesOption.prototype.updateSettingsValue = function () {
                    var pso = {
                        DeviceId: this.SourceId,
                        TopicId: this.MeasurementId,
                        UnitName: this.units,
                        Name: this.title,
                        Multiplier: this.multiplier,
                        DeviceName: this.DeviceName,
                        TopicName: this.TopicName
                    };
                    this.setting.Value = JSON.stringify(pso);
                    // the data series are assigned sequential number later
                    this.setting.Name = "PrimaryDataSeries99";
                    this.uniqueId = this.setting.Name;
                };
                return SeriesOption;
            }());
            EnergyEquivalencyDataSeries.SeriesOption = SeriesOption;
        })(EnergyEquivalencyDataSeries = SetupControl.EnergyEquivalencyDataSeries || (SetupControl.EnergyEquivalencyDataSeries = {}));
    })(SetupControl = Dashboards.SetupControl || (Dashboards.SetupControl = {}));
})(Dashboards || (Dashboards = {}));
//# sourceMappingURL=EnergyEquivalencyDataSeriesSetupControl.js.map