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 ConsumptionRanking = (function (_super) {
            __extends(ConsumptionRanking, _super);
            function ConsumptionRanking(gadgetOptions) {
                gadgetOptions.renderer = new Dashboards.Views.ConsumptionRankingRender();
                _super.call(this, gadgetOptions);
            }
            ConsumptionRanking.CreateInstance = function (gadgetOptions) {
                var instance = new ConsumptionRanking(gadgetOptions);
                return instance;
            };
            ConsumptionRanking.prototype.canExportData = function () {
                return false;
            };
            ConsumptionRanking.TypeId = "8fcaad83-fc60-4de6-ab89-a483580d846e";
            return ConsumptionRanking;
        }(Models.ChartingDataGadget));
        Models.ConsumptionRanking = ConsumptionRanking;
    })(Models = Dashboards.Models || (Dashboards.Models = {}));
})(Dashboards || (Dashboards = {}));
var Dashboards;
(function (Dashboards) {
    var Views;
    (function (Views) {
        var ConsumptionRankingRender = (function (_super) {
            __extends(ConsumptionRankingRender, _super);
            function ConsumptionRankingRender() {
                _super.call(this);
                this.chartVersion = 1; //Current Version of Heat Map
            }
            ConsumptionRankingRender.prototype.destroy = function () {
                _super.prototype.destroy.call(this);
                this.clearBarchart();
                this.clearPiechart();
                this.gadget = null;
            };
            /* Gadget Render Implementation
            **************************************************************************/
            ConsumptionRankingRender.prototype.updateGadget = function (handler) {
                var callBack = new Core.CallBack(this.renderContent, this);
                TemplateUtil.LocAndLoad(ConsumptionRankingRender.RenderTemplateUri, callBack);
            };
            /* Private Methods
            ******************************************************************************/
            ConsumptionRankingRender.prototype.renderContent = function (template) {
                if (!this.$gadgetRender)
                    return; // We have been destroyed!
                this.$gadgetRender.html(template);
                this.drawCharts();
                this.modifyVisiblityByRenderSize();
            };
            ConsumptionRankingRender.prototype.drawCharts = function () {
                if (!this.$gadgetRender)
                    return; // We have been destroyed!
                //Clear AmCharts on the page.
                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 legendName = this.getHandler().byName(Settings.Gadget.LegendName.name);
                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
                var chartPoints = [];
                var dps = [];
                var totalValue = 0;
                _.each(this.gadget.seriesMap, function (series) {
                    var chartPoint = {
                        "Name": series.title,
                        "Value": ISOGadgetsCommon.GadgetHelper.getFormattedNumber(dataPoints[series.name][0][Dashboards.Models.ChartingDataGadget.ValueIdx]),
                        "SeriesColor": series.color
                    };
                    totalValue += chartPoint.Value;
                    dps.push(chartPoint);
                });
                //Apply sorting on data
                var sortAscending = this.getHandler().byName(Settings.Gadget.SortOrder);
                var sdps = _.sortBy(dps, 'Value'); //default sort ascending.
                if (sortAscending.toString().toLowerCase() === 'false')
                    sdps = sdps.reverse();
                //////////////////////////////////////////////////
                ///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(totalValue, 2);
                    $total_area.html(totalText);
                    $total_area.prop('title', totalText);
                }
                var $chart_area = this.$gadgetRender.find('#consumptionrankingchart');
                $chart_area.height(this.$gadgetRender.height() - $total_area.height());
                //Find out position of bar from user settings and set the bar options
                //appropriately.
                var $pie_chart = this.$gadgetRender.find('#piechart');
                var barPosition = this.getHandler().byName(Settings.Gadget.BarPosition);
                this.piechart = this.getAmPieChart(sdps);
                this.piechart.write($pie_chart[0]);
                var $bar_chart = this.$gadgetRender.find('#barchart');
                this.barchart = this.getAmSerialChart(sdps, legendName, barPosition);
                this.barchart.write($bar_chart[0]);
            };
            ConsumptionRankingRender.prototype.clearBarchart = function () {
                if (!(_.isUndefined(this.barchart) || _.isNull(this.barchart))) {
                    this.barchart.clear();
                    this.barchart = null;
                }
            };
            ConsumptionRankingRender.prototype.clearPiechart = function () {
                if (!(_.isUndefined(this.piechart) || _.isNull(this.piechart))) {
                    this.piechart.clear();
                    this.piechart = null;
                }
            };
            ConsumptionRankingRender.prototype.rollOverPieChart = function (obj, index) {
                obj.piechart.rollOverSlice(index);
            };
            ConsumptionRankingRender.prototype.clearCursorPieChart = function (obj, index) {
                obj.piechart.rollOutSlice(index);
            };
            ConsumptionRankingRender.prototype.showCursorBarChart = function (obj, cursorName) {
                obj.barchart.chartCursor.showCursorAt(cursorName);
            };
            ConsumptionRankingRender.prototype.clearCursorBarChart = function (obj) {
                obj.barchart.chartCursor.hideCursor();
            };
            ConsumptionRankingRender.prototype.getAmSerialChart = function (data, legendString, barPosition) {
                var serialChart = new AmCharts.AmSerialChart();
                serialChart.dataProvider = data;
                serialChart.decimalSeparator = i18n.numberFormat.decimalDelimiter;
                serialChart.thousandsSeparator = i18n.numberFormat.thousandDelimiter;
                serialChart.valueAxes = [{
                        "title": legendString,
                        "gridColor": "#FFFFFF",
                        "gridAlpha": 0.2,
                        "dashLength": 0
                    }];
                serialChart.gridAboveGraphs = true;
                serialChart.rotate = (barPosition.toString().toLowerCase() === 'true');
                //serialChart.startDuration = 1;            
                var amGraphs = new AmCharts.AmGraph();
                amGraphs.balloonText = "[[category]]: <b>[[value]]</b>";
                amGraphs.fillAlphas = 0.8;
                amGraphs.lineAlpha = 0.2;
                amGraphs.type = "column";
                amGraphs.valueField = "Value";
                amGraphs.fillColorsField = "SeriesColor";
                serialChart.addGraph(amGraphs);
                serialChart.chartCursor = new AmCharts.ChartCursor();
                serialChart.chartCursor.categoryBalloonEnabled = false;
                serialChart.chartCursor.cursorAlpha = 0;
                serialChart.chartCursor.zoomable = false;
                serialChart.categoryField = "Name";
                serialChart.categoryAxis.gridPosition = "start";
                serialChart.categoryAxis.gridAlpha = 0;
                serialChart.categoryAxis.tickLength = 5;
                serialChart.categoryAxis.fontSize = '9';
                serialChart.categoryAxis.autoWrap = true;
                //serialChart.export = new AmCharts.ExportSettings();
                //serialChart.export.enabled = true;
                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 = [];
                        var srcHeader = i18n.loc.s('ISO50001Gadgets', 'Source');
                        var valHeader = i18n.loc.s('ISO50001Gadgets', 'Value');
                        _.each(data, function (item) {
                            var chartPoint = {};
                            chartPoint[srcHeader] = item['Name'];
                            chartPoint[valHeader] = i18n.formatNumber(item['Value']);
                            formattedData.push(chartPoint);
                        });
                        return formattedData;
                    }
                };
                return serialChart;
            };
            ConsumptionRankingRender.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 = "Value";
                pieChart.radius = "25%";
                pieChart.innerRadius = "50%";
                pieChart.labelText = "[[percents]]%";
                pieChart.fontSize = '9';
                pieChart.colorField = "SeriesColor";
                pieChart.startDuration = 0;
                var _this1 = this;
                pieChart.addListener("rollOverSlice", function (event) {
                    _this1.showCursorBarChart(_this1, event.dataItem.dataContext["Name"]);
                });
                pieChart.addListener("rollOutSlice", function (event) {
                    _this1.clearCursorBarChart(_this1);
                });
                return pieChart;
            };
            ///////////////////////////////////////////////////////////////////////
            //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//
            ///////////////////////////////////////////////////////////////////////
            ConsumptionRankingRender.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());
                }
            };
            ConsumptionRankingRender.RenderTemplateUri = 'Content/Gadgets/ConsumptionRanking/ConsumptionRanking.html';
            return ConsumptionRankingRender;
        }(Views.ViewPeriodChartRender));
        Views.ConsumptionRankingRender = ConsumptionRankingRender;
    })(Views = Dashboards.Views || (Dashboards.Views = {}));
})(Dashboards || (Dashboards = {}));
// Register the gadget type
Dashboards.Controllers.GadgetType.RegisterDefinition({
    typeId: Dashboards.Models.ConsumptionRanking.TypeId,
    create: Dashboards.Models.ConsumptionRanking.CreateInstance,
    resourceSet: 'ISO50001Gadgets'
});
//# sourceMappingURL=ConsumptionRanking.js.map