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 ParetoChart = (function (_super) {
            __extends(ParetoChart, _super);
            function ParetoChart(gadgetOptions) {
                gadgetOptions.renderer = new Dashboards.Views.ParetoChartRender();
                _super.call(this, gadgetOptions);
            }
            ParetoChart.CreateInstance = function (gadgetOptions) {
                var instance = new ParetoChart(gadgetOptions);
                return instance;
            };
            ParetoChart.prototype.canExportData = function () {
                return false;
            };
            //Overriden function of base class so as to normalize Pareto data points.        
            ParetoChart.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.
            ParetoChart.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[ParetoChart.CumPercentIdx] = origDataPoint.CumulativePercentage; //Add the cumulative percentage to list.                
                    newDataPoints[origDataPoint.SeriesName].push(dataPoint);
                });
                return newDataPoints;
            };
            ParetoChart.TypeId = "27de0b15-de1e-4e6e-89ce-751727148907";
            ParetoChart.CumPercentIdx = Models.ChartingDataGadget.TimeIdx + 1;
            return ParetoChart;
        }(Models.ChartingDataGadget));
        Models.ParetoChart = ParetoChart;
    })(Models = Dashboards.Models || (Dashboards.Models = {}));
})(Dashboards || (Dashboards = {}));
var Dashboards;
(function (Dashboards) {
    var Views;
    (function (Views) {
        var ParetoChartRender = (function (_super) {
            __extends(ParetoChartRender, _super);
            function ParetoChartRender() {
                _super.call(this);
                this.chartVersion = 1; //Current Version of Heat Map
            }
            ParetoChartRender.prototype.destroy = function () {
                _super.prototype.destroy.call(this);
                this.clearBarchart();
                this.gadget = null;
            };
            /* Gadget Render Implementation
            **************************************************************************/
            ParetoChartRender.prototype.updateGadget = function (handler) {
                var callBack = new Core.CallBack(this.renderContent, this);
                TemplateUtil.LocAndLoad(ParetoChartRender.RenderTemplateUri, callBack);
            };
            /* Private Methods
            ******************************************************************************/
            ParetoChartRender.prototype.renderContent = function (template) {
                if (!this.$gadgetRender)
                    return; // We have been destroyed!
                this.$gadgetRender.html(template);
                this.drawCharts();
                this.modifyVisiblityByRenderSize();
            };
            ///////////////////////////////////////////////////////////
            //Drawing Google Pareto chart now.
            ///////////////////////////////////////////////////////////
            ParetoChartRender.prototype.drawCharts = function () {
                var _this = this;
                if (!this.$gadgetRender)
                    return; // We have been destroyed!
                //Clear existing charts if any.
                this.clearBarchart();
                //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();
                this.dataPoints = $.extend(true, {}, this.gadget.dataSet.ChartingData.DataPoints); // Deep copy of data
                var markerValue = this.getHandler().byName(Settings.Gadget.ParetoMarkerPosition.name);
                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();
                //Now process the rows. For each data point, the first entry is the label, 
                //second entry is value (ignored), third entry is timestamp (ignored), fourth entry is cumulative percentage            
                var dps = [];
                var total = 0;
                _.each(this.gadget.seriesMap, function (series) {
                    if (_this.dataPoints && _this.dataPoints[series.name] && _this.dataPoints[series.name].length > 0) {
                        var value = ISOGadgetsCommon.GadgetHelper.getFormattedNumber(_this.dataPoints[series.name][0][Dashboards.Models.ChartingDataGadget.ValueIdx]);
                        var chartPoint = {
                            "Name": series.title,
                            "Value": value,
                            "Cumulative (%)": ISOGadgetsCommon.GadgetHelper.getFormattedNumber(_this.dataPoints[series.name][0][Dashboards.Models.ParetoChart.CumPercentIdx]),
                            "SeriesColor": series.color
                        };
                        dps.push(chartPoint);
                        total += value;
                    }
                });
                //Sort based on value as Paretos are sorted descending by default. 
                //This step is needed in spite of data reader sorting the data as the
                //above look on series map will push based on the order of series selected
                //by user.
                var sdps = _.sortBy(dps, "Value").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(total, 2);
                    $total_area.html(totalText);
                    $total_area.prop('title', totalText);
                }
                //Draw the bar chart now.            
                var $chart_area = this.$gadgetRender.find('#paretochart');
                $chart_area.height(this.$gadgetRender.height() - $total_area.height());
                this.paretochart = this.getParetoChart(sdps, legendName, Number(markerValue));
                this.paretochart.write($chart_area[0]);
            };
            ParetoChartRender.prototype.clearBarchart = function () {
                if (!(_.isUndefined(this.paretochart) || _.isNull(this.paretochart))) {
                    this.paretochart.clear();
                    this.paretochart = null;
                }
            };
            ParetoChartRender.prototype.getParetoChart = function (data, legend, marker) {
                var serialChart = new AmCharts.AmSerialChart();
                serialChart.dataProvider = data;
                serialChart.decimalSeparator = i18n.numberFormat.decimalDelimiter;
                serialChart.thousandsSeparator = i18n.numberFormat.thousandDelimiter;
                serialChart.valueAxes = [{
                        "id": "v1",
                        "title": legend,
                        "position": "left",
                        "autoGridCount": false
                    }, {
                        "id": "v2",
                        "title": i18n.loc.s('ISO50001Gadgets', 'Cumulative_Percent'),
                        "gridAlpha": 0,
                        "position": "right",
                        "autoGridCount": false,
                        "minimum": 0,
                        "guides": [{
                                "value": marker,
                                "inside": false,
                                "label": marker + "%",
                                "lineAlpha": 1,
                                "lineColor": "red",
                                "lineThickness": 4,
                                "color": 'red'
                            }]
                    }];
                serialChart.gridAboveGraphs = true;
                //serialChart.startDuration = 1;
                var amColGraph = new AmCharts.AmGraph();
                amColGraph.balloonText = "[[category]]: <b>[[value]]</b>";
                amColGraph.fillAlphas = 0.8;
                amColGraph.lineAlpha = 0.2;
                amColGraph.type = "column";
                amColGraph.valueField = "Value";
                amColGraph.valueAxis = serialChart.valueAxes[0];
                amColGraph.fillColorsField = "SeriesColor";
                var amLineGraph = new AmCharts.AmGraph();
                amLineGraph.balloonText = i18n.loc.s('ISO50001Gadgets', 'Cumulative_Percent') + " <b>[[value]]</b>";
                amLineGraph.lineColor = "black";
                amLineGraph.lineThickness = 2;
                amLineGraph.bullet = "round",
                    amLineGraph.bulletBorderAlpha = 1,
                    amLineGraph.bulletSize = 5,
                    amLineGraph.type = "smoothedLine";
                amLineGraph.valueField = "Cumulative (%)";
                amLineGraph.valueAxis = serialChart.valueAxes[1];
                serialChart.addGraph(amColGraph);
                serialChart.addGraph(amLineGraph);
                serialChart.chartCursor = new AmCharts.ChartCursor();
                serialChart.chartCursor.cursorPosition = "mouse";
                serialChart.chartCursor.categoryBalloonEnabled = 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 = {
                    "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');
                        var cumHeader = i18n.loc.s('ISO50001Gadgets', 'Cumulative_Percent');
                        _.each(data, function (item) {
                            var chartPoint = {};
                            chartPoint[srcHeader] = item['Name'];
                            chartPoint[valHeader] = i18n.formatNumber(item['Value']);
                            chartPoint[cumHeader] = i18n.formatNumber(item['Cumulative (%)']);
                            formattedData.push(chartPoint);
                        });
                        return formattedData;
                    }
                };
                return serialChart;
            };
            ///////////////////////////////////////////////////////////////////////
            //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//
            ///////////////////////////////////////////////////////////////////////
            ParetoChartRender.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());
                }
            };
            ParetoChartRender.RenderTemplateUri = 'Content/Gadgets/ParetoChart/ParetoChart.html';
            ParetoChartRender.totalHeaderHeight = 73;
            return ParetoChartRender;
        }(Views.ViewPeriodChartRender));
        Views.ParetoChartRender = ParetoChartRender;
    })(Views = Dashboards.Views || (Dashboards.Views = {}));
})(Dashboards || (Dashboards = {}));
//////////////////////////////////////////////
// Register the gadget type
//////////////////////////////////////////////
Dashboards.Controllers.GadgetType.RegisterDefinition({
    typeId: Dashboards.Models.ParetoChart.TypeId,
    create: Dashboards.Models.ParetoChart.CreateInstance,
    resourceSet: 'ISO50001Gadgets'
});
//# sourceMappingURL=ParetoChart.js.map