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 SankeyChart = (function (_super) {
            __extends(SankeyChart, _super);
            function SankeyChart(gadgetOptions) {
                gadgetOptions.renderer = new Dashboards.Views.SankeyRender();
                _super.call(this, gadgetOptions);
            }
            SankeyChart.CreateInstance = function (gadgetOptions) {
                var instance = new SankeyChart(gadgetOptions);
                return instance;
            };
            SankeyChart.prototype.canExportData = function () {
                return false;
            };
            //////////////////////////////////////////////////////////////////////////////////
            //Overriden to check for any license error for every gadget refresh.
            //////////////////////////////////////////////////////////////////////////////////
            SankeyChart.prototype.refreshDataSet = function (status, data) {
                this.InErrorState = false;
                if (!status.success) {
                    if (!_.isUndefined(status.xhr)) {
                        if (status.xhr.responseJSON.Details === 'ERR_INVALID_SANKEY_SOURCE') {
                            //AZZO license failure..Update the status message and mark gadget state as error
                            Dashboards.Views.Gadget.RenderStatusMessage(this.renderer.getDisplayFrame(), i18n.loc.unencoded('ISO50001Gadgets', 'Invalid_Sankey_source'));
                            this.InErrorState = true;
                            this.update(this.viewMode);
                        }
                    }
                }
                //No license error than let base class handle the refresh
                if (!this.InErrorState)
                    _super.prototype.refreshDataSet.call(this, status, data);
            };
            //Overriden function of base class so as to normalize Pareto data points.        
            SankeyChart.prototype.formatData = function (data) {
                var sankeyDataPoints = null;
                if (data && data.hasOwnProperty('ChartingData') && data.ChartingData && data.ChartingData.DataPoints) {
                    // Convert data format for standard Charting Data
                    sankeyDataPoints = 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(sankeyDataPoints)) {
                    data.ChartingData.DataPoints = this.normalizeChartingDataSeriesSankeyData(sankeyDataPoints);
                }
                return data;
            };
            //This function taken as is from Models.ChartingDataGadget and modified to add 
            //cumulative percentage to normalized data point.
            SankeyChart.prototype.normalizeChartingDataSeriesSankeyData = function (dataPoints) {
                var newDataPoints = {};
                _.each(dataPoints, function (origDataPoint) {
                    var seriesIdentifier = origDataPoint.SeriesName + '_' + origDataPoint.Target;
                    if (!newDataPoints[seriesIdentifier]) {
                        // Create array for series data values
                        newDataPoints[seriesIdentifier] = [];
                    }
                    var dataPoint = [];
                    dataPoint[Models.ChartingDataGadget.AxisLabelIdx] = origDataPoint.SeriesName;
                    dataPoint[Models.ChartingDataGadget.ValueIdx] = origDataPoint.Value;
                    dataPoint[Models.ChartingDataGadget.TimeIdx] = Date.ParseJsonDate(origDataPoint.TimestampLocal);
                    dataPoint[SankeyChart.TargetIdx] = origDataPoint.Target; //Add the target
                    dataPoint[SankeyChart.LevelIdx] = origDataPoint.Level; //Add the level
                    newDataPoints[seriesIdentifier].push(dataPoint);
                });
                return newDataPoints;
            };
            SankeyChart.TypeId = "0cb8e236-155c-480d-a13b-1bb1c07e4750";
            SankeyChart.TargetIdx = Models.ChartingDataGadget.TimeIdx + 1;
            SankeyChart.LevelIdx = SankeyChart.TargetIdx + 1;
            return SankeyChart;
        }(Models.ChartingDataGadget));
        Models.SankeyChart = SankeyChart;
    })(Models = Dashboards.Models || (Dashboards.Models = {}));
})(Dashboards || (Dashboards = {}));
var Dashboards;
(function (Dashboards) {
    var Views;
    (function (Views) {
        var SankeyRender = (function (_super) {
            __extends(SankeyRender, _super);
            function SankeyRender() {
                _super.call(this);
                this.chartVersion = 2; //Current Version of Sankey Gadget
            }
            SankeyRender.prototype.destroy = function () {
                _super.prototype.destroy.call(this);
                this.gadget = null;
            };
            /* Gadget Render Implementation
            **************************************************************************/
            SankeyRender.prototype.updateGadget = function (handler) {
                var callBack = new Core.CallBack(this.renderContent, this);
                TemplateUtil.LocAndLoad(SankeyRender.RenderTemplateUri, callBack);
            };
            /* Private Methods
            ******************************************************************************/
            SankeyRender.prototype.renderContent = function (template) {
                if (!this.$gadgetRender)
                    return; // We have been destroyed!
                this.$gadgetRender.html(template);
                this.drawCharts();
                this.modifyVisiblityByRenderSize();
            };
            SankeyRender.prototype.drawCharts = function () {
                if (!this.$gadgetRender)
                    return; // We have been destroyed!
                //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 unique_colours_settings = this.getHandler().byName(Settings.Gadget.ApplyUniqueColours.name);
                //Default setting value
                var setting = {
                    "Theme": {
                        "Key": "A",
                        "Value": "#006699"
                    },
                    "FlowColor": {
                        "Key": "source",
                        "Value": "#666666"
                    },
                    "ShowLabels": "true",
                    "ShowNodeTotals": "true",
                    "FontColor": "#000000",
                    "LabelSuffix": " " + JSON.parse(this.getHandler().byName('PrimaryDataSeries1')).UnitName,
                    "Background_color": this.$gadgetContent.css('background-color'),
                    "show_data_warning": this.getHandler().byName(Settings.Gadget.ShowDataWarning.name) === 'true',
                    "apply_unique_colours": _.isNull(unique_colours_settings) || _.isUndefined(unique_colours_settings) ? false : unique_colours_settings === 'true'
                };
                var dataPoints = _.values($.extend(true, {}, this.gadget.dataSet.ChartingData.DataPoints)); // Deep copy of data
                var dps = [];
                _.each(dataPoints, function (point) {
                    var sankeyPoint = point[0];
                    dps.push({ target: sankeyPoint[0], value: sankeyPoint[1], source: sankeyPoint[3], level: sankeyPoint[4] });
                });
                var $chart = this.$gadgetRender.find('#sankey');
                var $message_area = $chart.find('#message');
                var $chart_area = $chart.find('#chart');
                $chart_area.height(this.$gadgetRender.height() - $message_area.height() - 20);
                this.clearSankey($chart_area.selector, $message_area.selector);
                setting['canvas_height'] = $chart_area.height() - 5;
                setting['canvas_width'] = $chart_area.width();
                setting['font_size'] = setting['canvas_width'] * 0.005 + setting['canvas_height'] * 0.003;
                //Loop till we could render the sankey in given space or the total data points are exhausted during the process.
                while (!process_sankey(dps, setting, $chart_area.selector, $message_area.selector)) {
                    //Sankey could not be generated in given size...let us increment by 50 pixels and
                    //reattempt
                    this.clearSankey($chart_area.selector, $message_area.selector);
                    setting['canvas_height'] = setting['canvas_height'] + 50;
                    setting['canvas_width'] = setting['canvas_width'] + 50;
                }
            };
            SankeyRender.prototype.clearSankey = function (chartselector, msgselector) {
                function clear_sankey() {
                    $(chartselector).html('');
                    $(msgselector).html('');
                    $(msgselector).hide();
                }
            };
            SankeyRender.prototype.addErrorMessage = function (msgselector, msg) {
                $(msgselector).show();
                $(msgselector).html(msg);
            };
            ///////////////////////////////////////////////////////////////////////
            //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//
            ///////////////////////////////////////////////////////////////////////
            SankeyRender.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());
                    this.getHandler().setting(Settings.Gadget.ShowDataWarning, "true");
                }
            };
            SankeyRender.RenderTemplateUri = 'Content/Gadgets/Sankey/SankeyGadget.html';
            return SankeyRender;
        }(Views.ViewPeriodChartRender));
        Views.SankeyRender = SankeyRender;
    })(Views = Dashboards.Views || (Dashboards.Views = {}));
})(Dashboards || (Dashboards = {}));
// Register the gadget type
Dashboards.Controllers.GadgetType.RegisterDefinition({
    typeId: Dashboards.Models.SankeyChart.TypeId,
    create: Dashboards.Models.SankeyChart.CreateInstance,
    resourceSet: 'ISO50001Gadgets'
});
//# sourceMappingURL=SankeyGadget.js.map