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 __());
};
/************************************************
Blank Space Gadget
************************************************/
var Dashboards;
(function (Dashboards) {
    var Models;
    (function (Models) {
        var IntervalConsumptionRanking = (function (_super) {
            __extends(IntervalConsumptionRanking, _super);
            function IntervalConsumptionRanking(gadgetOptions) {
                gadgetOptions.renderer = new Dashboards.Views.IntervalConsumptionRankingRender();
                _super.call(this, gadgetOptions);
            }
            IntervalConsumptionRanking.CreateInstance = function (gadgetOptions) {
                var instance = new IntervalConsumptionRanking(gadgetOptions);
                return instance;
            };
            IntervalConsumptionRanking.prototype.canExportData = function () {
                return false;
            };
            //Overriden function of base class so as to normalize Pareto data points.        
            IntervalConsumptionRanking.prototype.formatData = function (data) {
                var paretoDataPoints = null;
                if (data && data.hasOwnProperty('ChartingData') && data.ChartingData && data.ChartingData.DataPoints) {
                    // Convert data format for standard Charting Data
                    paretoDataPoints = data.ChartingData.DataPoints;
                }
                //Let the chart data gadget base class execute first
                _super.prototype.formatData.call(this, data);
                //Now let us normalize the pareto data point.
                if (!_.isNull(paretoDataPoints)) {
                    data.ChartingData.DataPoints = this.normalizeChartingDataSeriesParetoData(paretoDataPoints);
                }
                return data;
            };
            //This function taken as is from Models.ChartingDataGadget and modified to add 
            //cumulative percentage to normalized data point.
            IntervalConsumptionRanking.prototype.normalizeChartingDataSeriesParetoData = function (dataPoints) {
                var newDataPoints = {};
                _.each(dataPoints, function (origDataPoint) {
                    if (!newDataPoints[origDataPoint.SeriesName]) {
                        // Create array for series data values
                        newDataPoints[origDataPoint.SeriesName] = [];
                    }
                    var dataPoint = [];
                    dataPoint[Models.ChartingDataGadget.AxisLabelIdx] = origDataPoint.TimeLabel;
                    dataPoint[Models.ChartingDataGadget.ValueIdx] = origDataPoint.Value;
                    dataPoint[Models.ChartingDataGadget.TimeIdx] = Date.ParseJsonDate(origDataPoint.TimestampLocal);
                    dataPoint[IntervalConsumptionRanking.DataPointIdx] = origDataPoint.DataPoints; //Add the cumulative percentage to list.
                    newDataPoints[origDataPoint.SeriesName].push(dataPoint);
                });
                return newDataPoints;
            };
            IntervalConsumptionRanking.TypeId = "a2ff42f0-0f16-4dee-8f82-7c153b02cd50";
            IntervalConsumptionRanking.DataPointIdx = Models.ChartingDataGadget.TimeIdx + 1;
            return IntervalConsumptionRanking;
        }(Models.ChartingDataGadget));
        Models.IntervalConsumptionRanking = IntervalConsumptionRanking;
    })(Models = Dashboards.Models || (Dashboards.Models = {}));
})(Dashboards || (Dashboards = {}));
var Dashboards;
(function (Dashboards) {
    var Views;
    (function (Views) {
        var IntervalConsumptionRankingRender = (function (_super) {
            __extends(IntervalConsumptionRankingRender, _super);
            function IntervalConsumptionRankingRender() {
                _super.call(this);
                this.chartVersion = 1; //Current Version of Heat Map
            }
            IntervalConsumptionRankingRender.prototype.destroy = function () {
                _super.prototype.destroy.call(this);
                this.clearBarchart();
                this.clearPiechart();
                this.gadget = null;
            };
            /* Gadget Render Implementation
            **************************************************************************/
            IntervalConsumptionRankingRender.prototype.updateGadget = function (handler) {
                var callBack = new Core.CallBack(this.renderContent, this);
                TemplateUtil.LocAndLoad(IntervalConsumptionRankingRender.RenderTemplateUri, callBack);
            };
            /* Private Methods
            ******************************************************************************/
            IntervalConsumptionRankingRender.prototype.renderContent = function (template) {
                if (!this.$gadgetRender)
                    return; // We have been destroyed!
                this.$gadgetRender.html(template);
                this.drawCharts();
                this.modifyVisiblityByRenderSize();
            };
            IntervalConsumptionRankingRender.prototype.drawCharts = function () {
                var _this = this;
                if (!this.$gadgetRender)
                    return; // We have been destroyed!
                this.clearBarchart();
                this.clearPiechart();
                //Handle any older gadget instances if any. Handles the 
                //setting default values for new settings. When old instances
                //are saved the new gadgets parameters are saved in gadgetXML.
                this.updateChartVersion();
                var showTotal = this.getHandler().byName(Settings.Gadget.ShowTotal.name);
                //Older gadgets will not have this setting. Hence handle nulls
                showTotal = _.isUndefined(showTotal) || _.isNull(showTotal) ? 'true' : showTotal.toLowerCase();
                var dataPoints = $.extend(true, {}, this.gadget.dataSet.ChartingData.DataPoints); // Deep copy of data
                //Apply sorting on data
                var sortAscending = this.getHandler().byName(Settings.Gadget.SortOrder);
                var sdps = _.sortBy(dataPoints.StackedDataPoint, '1'); //default sort ascending.
                if (sortAscending.toString().toLowerCase() === 'false')
                    sdps = sdps.reverse();
                //Form bar chart data points
                var barChartData = [];
                _.each(sdps, function (dataPoint) {
                    var chartPoint = {};
                    chartPoint["Name"] = dataPoint[Dashboards.Models.ChartingDataGadget.AxisLabelIdx];
                    chartPoint["Timestamp"] = _this.getDateFormatString(dataPoint[Dashboards.Models.ChartingDataGadget.TimeIdx], dataPoint[Dashboards.Models.ChartingDataGadget.AxisLabelIdx]);
                    _.each(_this.gadget.seriesMap, function (series) {
                        var p = _this.getDataPointFromSeriesName(dataPoint[Dashboards.Models.IntervalConsumptionRanking.DataPointIdx], series.name);
                        if (!_.isUndefined(p)) {
                            chartPoint[series.title] = ISOGadgetsCommon.GadgetHelper.getFormattedNumber(p.Value);
                            chartPoint[series.title + "~Color"] = series.color;
                        }
                    });
                    barChartData.push(chartPoint);
                });
                //Form pie chart data points
                var total = 0;
                var pieChartData = [];
                _.each(sdps, function (dataPoint) {
                    var piePoint = {};
                    piePoint["Name"] = dataPoint[Dashboards.Models.ChartingDataGadget.AxisLabelIdx];
                    piePoint["Timestamp"] = _this.getDateFormatString(dataPoint[Dashboards.Models.ChartingDataGadget.TimeIdx], dataPoint[Dashboards.Models.ChartingDataGadget.AxisLabelIdx]);
                    var sum = 0;
                    _.each(_this.gadget.seriesMap, function (series) {
                        var p = _this.getDataPointFromSeriesName(dataPoint[Dashboards.Models.IntervalConsumptionRanking.DataPointIdx], series.name);
                        if (!_.isUndefined(p)) {
                            sum = sum + p.Value;
                        }
                    });
                    piePoint["Total"] = ISOGadgetsCommon.GadgetHelper.getFormattedNumber(sum);
                    pieChartData.push(piePoint);
                    total += piePoint["Total"];
                });
                //////////////////////////////////////////////////
                ///Populate the total div to display total of all values.
                //In addition, resize the chart area without which chart
                //will go out of the gadget. Chart is resized based on renderer
                //height and height of total div area.
                /////////////////////////////////////////////////////
                var $total_area = this.$gadgetRender.find('#totalvalue');
                if (showTotal === 'true') {
                    var totalText = i18n.loc.s('ISO50001Gadgets', 'Gadget_Total') + ': ' + i18n.formatNumber(total, 2);
                    $total_area.html(totalText);
                    $total_area.prop('title', totalText);
                }
                var $chart_area = this.$gadgetRender.find('#intervalconsumptionrankingchart');
                $chart_area.height(this.$gadgetRender.height() - $total_area.height());
                //draw bar chart
                var $barchart = this.$gadgetRender.find('#intervalbarchart');
                var barPosition = this.getHandler().byName(Settings.Gadget.BarPosition);
                this.stackedbarchart = this.getAmSerialChart(barChartData, barPosition);
                this.stackedbarchart.write($barchart[0]);
                //draw pie chart
                var $piechart = this.$gadgetRender.find('#intervalpiechart');
                this.piechart = this.getAmPieChart(pieChartData);
                this.piechart.write($piechart[0]);
            };
            IntervalConsumptionRankingRender.prototype.clearBarchart = function () {
                if (!(_.isUndefined(this.stackedbarchart) || _.isNull(this.stackedbarchart))) {
                    this.stackedbarchart.clear();
                    this.stackedbarchart = null;
                }
            };
            IntervalConsumptionRankingRender.prototype.clearPiechart = function () {
                if (!(_.isUndefined(this.piechart) || _.isNull(this.piechart))) {
                    this.piechart.clear();
                    this.piechart = null;
                }
            };
            IntervalConsumptionRankingRender.prototype.rollOverPieChart = function (obj, index) {
                obj.piechart.rollOverSlice(index);
            };
            IntervalConsumptionRankingRender.prototype.clearCursorPieChart = function (obj, index) {
                obj.piechart.rollOutSlice(index);
            };
            IntervalConsumptionRankingRender.prototype.getAmSerialChart = function (data, barPosition) {
                var serialChart = new AmCharts.AmSerialChart();
                serialChart.decimalSeparator = i18n.numberFormat.decimalDelimiter;
                serialChart.thousandsSeparator = i18n.numberFormat.thousandDelimiter;
                serialChart.dataProvider = data;
                serialChart.valueAxes = [{
                        "stackType": "regular",
                        "axisAlpha": 0.3,
                        "gridAlpha": 0
                    }];
                serialChart.gridAboveGraphs = true;
                serialChart.rotate = (barPosition.toString().toLowerCase() === 'true');
                //serialChart.startDuration = 1;
                serialChart.categoryField = "Name";
                serialChart.categoryAxis.gridPosition = "start";
                serialChart.categoryAxis.gridAlpha = 0;
                serialChart.categoryAxis.axisAlpha = 20;
                serialChart.categoryAxis.position = 'left';
                serialChart.categoryAxis.fontSize = '9';
                if (data.length > 0) {
                    _.each(this.gadget.seriesMap, function (series) {
                        var amGraphs = new AmCharts.AmGraph();
                        amGraphs.balloonText = "<b>[[title]]</b><br><span style='font-size:14px'>[[description]]: <b>[[value]]</b></span>";
                        amGraphs.fillAlphas = 0.8;
                        amGraphs.lineAlpha = 0.2;
                        amGraphs.title = series.title;
                        amGraphs.type = "column";
                        amGraphs.descriptionField = "Timestamp"; //use the description field for timestamp
                        amGraphs.valueField = series.title;
                        amGraphs.fillColorsField = series.title + "~Color";
                        amGraphs.legendColor = series.color;
                        amGraphs.color = "#000000";
                        serialChart.addGraph(amGraphs);
                    });
                }
                var legend = new AmCharts.AmLegend();
                legend.maxColumns = data.length;
                legend.position = "bottom";
                legend.fontSize = 9;
                legend.markerType = "circle";
                legend.markerSize = 9;
                legend.valueText = "";
                serialChart.addLegend(legend);
                var _this1 = this;
                serialChart.addListener("rollOverGraphItem", function (event) {
                    _this1.rollOverPieChart(_this1, event.index);
                });
                serialChart.addListener("rollOutGraphItem", function (event) {
                    _this1.clearCursorPieChart(_this1, event.index);
                });
                serialChart.export = {
                    "enabled": true,
                    "libs": { "autoLoad": false },
                    "fileName": this.title,
                    "menu": [{
                            "class": "export-main",
                            "icon": "export_16.png",
                            "menu": ["CSV", "XLSX"]
                        }],
                    "processData": function (data) {
                        var formattedData = [];
                        _.each(data, function (item) {
                            var chartPoint = {};
                            _.mapObject(item, function (val, key) {
                                key = key == 'Name' ? '' : key;
                                if (!key.endsWith('~Color')) {
                                    var header = key;
                                    if (key == 'Timestamp')
                                        header = i18n.loc.s('ISO50001Gadgets', 'Timestamp');
                                    else if (key != '')
                                        val = _.isUndefined(val) ? '' : i18n.formatNumber(val);
                                    chartPoint[header] = val;
                                }
                                return val; //just return the val since we do not want to modify existing item.
                            });
                            if (_.keys(chartPoint).length > 2)
                                formattedData.push(chartPoint);
                        });
                        return formattedData;
                    }
                };
                return serialChart;
            };
            IntervalConsumptionRankingRender.prototype.getAmPieChart = function (data) {
                var pieChart = new AmCharts.AmPieChart("light");
                pieChart.decimalSeparator = i18n.numberFormat.decimalDelimiter;
                pieChart.thousandsSeparator = i18n.numberFormat.thousandDelimiter;
                pieChart.dataProvider = data;
                pieChart.titleField = "Name";
                pieChart.valueField = "Total";
                pieChart.radius = "25%";
                pieChart.innerRadius = "50%";
                pieChart.descriptionField = "Timestamp";
                pieChart.labelText = "[[title]]";
                pieChart.fontSize = '9';
                pieChart.colorField = "SeriesColor";
                pieChart.startDuration = 0;
                return pieChart;
            };
            ///////////////////////////////////////////////////////////////////////////////////////
            //Get the dateformat to be shown in chart tool tips later. The date time is based on 
            //viewing period and aggregation. Hence call base classes to get the appropriate
            //date format string and return accordingly
            ///////////////////////////////////////////////////////////////////////////////////////
            IntervalConsumptionRankingRender.prototype.getDateFormatString = function (date, label) {
                var handler = this.getHandler();
                var viewPeriodKey = this.gadget.getViewPeriodId(handler);
                var viewPeriodGroup = this.gadget.getViewPeriodGroup(handler);
                var aggregationKey = this.gadget.getViewPeriodAggregationId(handler);
                var dateFormatString = Settings.ViewingPeriod.GetSimpleDateFormatStringForViewingPeriod(viewPeriodGroup.Name, viewPeriodKey, aggregationKey);
                // If the format string has the time, we want to use the 
                // axis label value since the date of the value is the 
                // interval time, but we want to output the aggregated hour
                var timeLabel = (dateFormatString.toLowerCase().indexOf('h') > -1)
                    ? i18n.formatDate(date, i18n.dateFormat.shortDate) + ' ' + label
                    : i18n.formatDate(date, dateFormatString);
                return timeLabel;
            };
            //////////////////////////////////////////////////////////
            //Gets the appropriate data point based on series name.
            //////////////////////////////////////////////////////////
            IntervalConsumptionRankingRender.prototype.getDataPointFromSeriesName = function (list, seriesName) {
                return _.findWhere(list, { SeriesName: seriesName });
            };
            ///////////////////////////////////////////////////////////////////////
            //Function to take care of gadget upgrade case. Compares the instance//
            //version with the gadgets current version and takes actions like //
            //setting default values of newly introduced gadget parameters//
            ///////////////////////////////////////////////////////////////////////
            IntervalConsumptionRankingRender.prototype.updateChartVersion = function () {
                var instanceVersion = Number(this.getHandler().byName(Settings.Gadget.Version.name));
                if (instanceVersion < this.chartVersion) {
                    //Set default values for newly added config settings.
                    this.getHandler().setting(Settings.Gadget.Version, this.chartVersion.toString());
                }
            };
            IntervalConsumptionRankingRender.RenderTemplateUri = 'Content/Gadgets/IntervalConsumptionRanking/IntervalConsumptionRanking.html';
            return IntervalConsumptionRankingRender;
        }(Views.ViewPeriodChartRender));
        Views.IntervalConsumptionRankingRender = IntervalConsumptionRankingRender;
    })(Views = Dashboards.Views || (Dashboards.Views = {}));
})(Dashboards || (Dashboards = {}));
// Register the gadget type
Dashboards.Controllers.GadgetType.RegisterDefinition({
    typeId: Dashboards.Models.IntervalConsumptionRanking.TypeId,
    create: Dashboards.Models.IntervalConsumptionRanking.CreateInstance,
    resourceSet: 'ISO50001Gadgets'
});
//# sourceMappingURL=IntervalConsumptionRanking.js.map