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 IntervalParetoChart = (function (_super) {
            __extends(IntervalParetoChart, _super);
            function IntervalParetoChart(gadgetOptions) {
                gadgetOptions.renderer = new Dashboards.Views.IntervalParetoChartRender();
                _super.call(this, gadgetOptions);
            }
            IntervalParetoChart.CreateInstance = function (gadgetOptions) {
                var instance = new IntervalParetoChart(gadgetOptions);
                return instance;
            };
            IntervalParetoChart.prototype.canExportData = function () {
                return false;
            };
            //Overriden function of base class so as to normalize Pareto data points.        
            IntervalParetoChart.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.
            IntervalParetoChart.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[IntervalParetoChart.CumPercentIdx] = origDataPoint.CumulativePercentage; //Add the cumulative percentage to list.
                    dataPoint[IntervalParetoChart.DataPointIdx] = origDataPoint.DataPoints; //Add the cumulative percentage to list.
                    newDataPoints[origDataPoint.SeriesName].push(dataPoint);
                });
                return newDataPoints;
            };
            IntervalParetoChart.TypeId = "36144e8f-ff1d-47eb-aca2-89c2f86ba411";
            IntervalParetoChart.CumPercentIdx = Models.ChartingDataGadget.TimeIdx + 1;
            IntervalParetoChart.DataPointIdx = Models.ChartingDataGadget.TimeIdx + 2;
            return IntervalParetoChart;
        }(Models.ChartingDataGadget));
        Models.IntervalParetoChart = IntervalParetoChart;
    })(Models = Dashboards.Models || (Dashboards.Models = {}));
})(Dashboards || (Dashboards = {}));
var Dashboards;
(function (Dashboards) {
    var Views;
    (function (Views) {
        var IntervalParetoChartRender = (function (_super) {
            __extends(IntervalParetoChartRender, _super);
            function IntervalParetoChartRender() {
                _super.call(this);
                this.chartVersion = 1; //Current Version of Heat Map
            }
            IntervalParetoChartRender.prototype.destroy = function () {
                _super.prototype.destroy.call(this);
                this.clearBarchart();
                this.gadget = null;
            };
            /* Gadget Render Implementation
            **************************************************************************/
            IntervalParetoChartRender.prototype.updateGadget = function (handler) {
                var callBack = new Core.CallBack(this.renderContent, this);
                TemplateUtil.LocAndLoad(IntervalParetoChartRender.RenderTemplateUri, callBack);
            };
            /* Private Methods
            ******************************************************************************/
            IntervalParetoChartRender.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.
            ///////////////////////////////////////////////////////////
            IntervalParetoChartRender.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();
                var dataPoints = $.extend(true, {}, this.gadget.dataSet.ChartingData.DataPoints); // Deep copy of data
                var markerValue = this.getHandler().byName(Settings.Gadget.ParetoMarkerPosition.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 barChartData = [];
                var total = 0;
                _.each(dataPoints.Pareto, 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]);
                    //No data points (missing logs\nulls) avoid the cumulative line
                    if (dataPoint[Dashboards.Models.IntervalParetoChart.DataPointIdx].length > 0)
                        chartPoint["Cumulative (%)"] = ISOGadgetsCommon.GadgetHelper.getFormattedNumber(dataPoint[Dashboards.Models.IntervalParetoChart.CumPercentIdx]);
                    _.each(_this.gadget.seriesMap, function (series) {
                        var p = _this.getDataPointFromSeriesName(dataPoint[Dashboards.Models.IntervalParetoChart.DataPointIdx], series.name);
                        if (!_.isUndefined(p)) {
                            var value = ISOGadgetsCommon.GadgetHelper.getFormattedNumber(p.Value);
                            chartPoint[series.title] = value;
                            chartPoint[series.title + "~Color"] = series.color;
                            total += value;
                        }
                    });
                    barChartData.push(chartPoint);
                });
                var sdps = _.sortBy(barChartData, "Cumulative (%)");
                //////////////////////////////////////////////////
                ///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('#intervalparetochart');
                $chart_area.height(this.$gadgetRender.height() - $total_area.height());
                this.stackedcolumnchart = this.getAmSerialChart(sdps, Number(markerValue));
                this.stackedcolumnchart.write($chart_area[0]);
            };
            IntervalParetoChartRender.prototype.clearBarchart = function () {
                if (!(_.isUndefined(this.stackedcolumnchart) || _.isNull(this.stackedcolumnchart))) {
                    this.stackedcolumnchart.clear();
                    this.stackedcolumnchart = null;
                }
            };
            //////////////////////////////////////////////////////////
            //Gets the appropriate data point based on series name.
            //////////////////////////////////////////////////////////
            IntervalParetoChartRender.prototype.getDataPointFromSeriesName = function (list, seriesName) {
                return _.findWhere(list, { SeriesName: seriesName });
            };
            IntervalParetoChartRender.prototype.getAmSerialChart = function (data, 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",
                        "stackType": "regular",
                        "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;
                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.labelText = "[[percents]]%";
                        amGraphs.lineAlpha = 0.2;
                        amGraphs.title = series.title;
                        amGraphs.descriptionField = "Timestamp"; //use the description field for timestamp
                        amGraphs.type = "column";
                        amGraphs.valueField = series.title;
                        amGraphs.color = "#000000";
                        amGraphs.valueAxis = serialChart.valueAxes[0];
                        amGraphs.fillColorsField = series.title + "~Color";
                        amGraphs.legendColor = series.color;
                        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 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];
                    amLineGraph.fillColorsField = "color";
                    amLineGraph.visibleInLegend = false;
                    serialChart.addGraph(amLineGraph);
                }
                serialChart.chartCursor = new AmCharts.ChartCursor();
                serialChart.chartCursor.cursorPosition = "mouse";
                serialChart.chartCursor.categoryBalloonEnabled = false;
                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 tsheader = i18n.loc.s('ISO50001Gadgets', 'Timestamp');
                        ;
                        var cumheader = i18n.loc.s('ISO50001Gadgets', 'Cumulative_Percent');
                        _.each(data, function (item) {
                            var chartPoint = {};
                            _.mapObject(item, function (val, key) {
                                key = key == 'Name' ? '' : key;
                                if (!key.endsWith('~Color') && !_.isUndefined(val)) {
                                    var header = key;
                                    if (key == 'Timestamp')
                                        header = tsheader;
                                    else if (key == 'Cumulative (%)')
                                        header = cumheader;
                                    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;
            };
            ///////////////////////////////////////////////////////////////////////////////////////
            //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
            ///////////////////////////////////////////////////////////////////////////////////////
            IntervalParetoChartRender.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;
            };
            ///////////////////////////////////////////////////////////////////////
            //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//
            ///////////////////////////////////////////////////////////////////////
            IntervalParetoChartRender.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());
                }
            };
            IntervalParetoChartRender.RenderTemplateUri = 'Content/Gadgets/IntervalParetoChart/IntervalParetoChart.html';
            IntervalParetoChartRender.totalHeaderHeight = 73;
            return IntervalParetoChartRender;
        }(Views.ViewPeriodChartRender));
        Views.IntervalParetoChartRender = IntervalParetoChartRender;
    })(Views = Dashboards.Views || (Dashboards.Views = {}));
})(Dashboards || (Dashboards = {}));
//////////////////////////////////////////////
// Register the gadget type
//////////////////////////////////////////////
Dashboards.Controllers.GadgetType.RegisterDefinition({
    typeId: Dashboards.Models.IntervalParetoChart.TypeId,
    create: Dashboards.Models.IntervalParetoChart.CreateInstance,
    resourceSet: 'ISO50001Gadgets'
});
//# sourceMappingURL=IntervalParetoChart.js.map