/*
THIS INFRAGISTICS ULTIMATE SOFTWARE LICENSE  AGREEMENT ("AGREEMENT") LOCATED HERE:
https://www.infragistics.com/legal/license/igultimate-la
https://www.infragistics.com/legal/license/igultimate-eula
GOVERNS THE LICENSING, INSTALLATION AND USE OF INFRAGISTICS SOFTWARE. BY DOWNLOADING AND/OR INSTALLING AND USING INFRAGISTICS SOFTWARE:  you are indicating that you have read and understand this Agreement, and agree to be legally bound by it on behalf of the yourself and your company.
*/
import * as tslib_1 from "tslib";
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { GridMode_$type } from './GridMode';
import { IgrSeriesViewer } from './igr-series-viewer';
import { ReactRenderer, ReactWrapper } from "igniteui-react-core/ES5/react-renderer";
import { TypeRegistrar } from "igniteui-react-core/ES5/type";
import { XamDataChart } from './XamDataChart';
import { CollectionAdapter, brushToString, stringToBrush, fromBrushCollection, toBrushCollection, ensureBool, ensureEnum } from "igniteui-react-core/ES5/componentUtil";
import { Axis } from './Axis';
import { DataChartStylingDefaults } from './DataChartStylingDefaults';
import { DataContext } from "igniteui-react-core/ES5/igr-data-context";
import { SeriesCollection } from './igr-series-collection';
import { NotifyCollectionChangedAction } from "igniteui-react-core/ES5/NotifyCollectionChangedAction";
import { AxisCollection } from './igr-axis-collection';
/**
 * Represents a chart area containing axes, series, an optional legend and other hosted content.
*/
var IgrDataChart = /** @class */ (function (_super) {
    tslib_1.__extends(IgrDataChart, _super);
    function IgrDataChart(props) {
        var _this = _super.call(this, props) || this;
        _this.contentAxes = [];
        _this.contentSeries = [];
        _this._contentChildren = null;
        _this._contentChildrenActual = null;
        _this._contentChildrenMap = null;
        _this._contentChildrenUnresolved = 0;
        /**
         * The series actually present in the chart. Do not directly modify this array.
         * This array's contents can be modified by causing React to reproject the child content.
         * Or adding and removing series from the manual series collection on the series property.
         */
        _this.actualSeries = [];
        /**
         * The axes actually present in the chart. Do not directly modify this array.
         * This array's contents can be modified by causing React to reproject the child content.
         * Or adding and removing axes from the manual axes collection on the axes property.
         */
        _this.actualAxes = [];
        _this._series = null;
        _this._axes = null;
        _this._initialized = false;
        _this._axesAdapter = null;
        _this._seriesAdapter = null;
        _this._defaultTooltips = null;
        _this._uniqueTooltipId = 0;
        _this._tooltipRef = _this._tooltipRef.bind(_this);
        _this.getSeriesRef = _this.getSeriesRef.bind(_this);
        _this._activeTooltipElements = new Map();
        _this._activeTooltips = new Map();
        _this._currentTooltips = [];
        if (document) {
            _this._container = document.createElement("div");
            _this._container.style.display = "block";
            _this._container.style.width = "100%";
            _this._container.style.height = "100%";
        }
        var root;
        root = _this._container;
        var ren = new ReactRenderer(root, document, true, DataChartStylingDefaults);
        _this._wrapper = ren;
        var chart = _this.i;
        _this._chart = chart;
        chart.provideContainer(ren);
        ren.addSizeWatcher(function () {
            _this._chart.notifyContainerResized();
        });
        _this._initialized = true;
        return _this;
    }
    Object.defineProperty(IgrDataChart.prototype, "height", {
        get: function () {
            return this._height;
        },
        set: function (value) {
            this._height = value;
            if (this._elRef) {
                this._elRef.style.height = value;
                this._chart.notifyContainerResized();
            }
        },
        enumerable: true,
        configurable: true
    });
    IgrDataChart.prototype._updateContentChildren = function () {
        this.contentAxes = [];
        this.contentSeries = [];
        for (var i = 0; i < this._contentChildrenActual.length; i++) {
            if ((Axis.$type).isAssignableFrom(this._contentChildrenActual[i].i.$type)) {
                this.contentAxes.push(this._contentChildrenActual[i]);
            }
            else {
                this.contentSeries.push(this._contentChildrenActual[i]);
            }
        }
        if (this._axesAdapter !== null) {
            this._axesAdapter.notifyContentChanged();
        }
        if (this._seriesAdapter !== null) {
            this._seriesAdapter.notifyContentChanged();
        }
    };
    IgrDataChart.prototype.getSeriesRef = function (child) {
        console.log(child);
        if (child === null) {
            return;
        }
        var index = this._contentChildrenMap.get(child.name);
        if (this._contentChildrenActual[index] === null) {
            this._contentChildrenActual[index] = child;
            this._contentChildrenUnresolved--;
            if (this._contentChildrenUnresolved <= 0) {
                this._updateContentChildren();
            }
        }
    };
    IgrDataChart.prototype._childrenDiffer = function (children) {
        if (this._contentChildren === null) {
            return true;
        }
        if (React.Children.count(children) != this._contentChildren.length) {
            return true;
        }
        var arr = React.Children.toArray(children);
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].props.name !== this._contentChildren[i].props.name) {
                return true;
            }
        }
        return false;
    };
    IgrDataChart.prototype.render = function () {
        // if (!this._childrenDiffer(this.props.children)) {
        // 	let div = React.createElement("div", {
        // 		ref: (ref) => {
        // 			this._elRef = ref;
        // 		},
        // 		children: this.props.children
        // 	});
        var _this = this;
        // 	return div;
        // } else {
        var children = null;
        var c = React.Children.map(this.props.children, function (ch) {
            var key = ch.props.key || ch.props.name;
            if (key === undefined) {
                throw new Error("each child of chart must have a unique key or name property");
            }
            return React.cloneElement(ch, {
                key: key,
                ref: _this.getSeriesRef
            });
        });
        children = c;
        this._contentChildren = c;
        this._contentChildrenActual = [];
        this._contentChildrenMap = new Map();
        this._contentChildren.map(function (ch, i) {
            _this._contentChildrenMap.set(ch.props.name, i);
            _this._contentChildrenActual[i] = null;
        });
        this._contentChildrenUnresolved = this._contentChildrenMap.size;
        if (this._currentTooltips && this._currentTooltips.length > 0) {
            children = React.Children.toArray(this.props.children);
            for (var i = 0; i < this._currentTooltips.length; i++) {
                var t = this._currentTooltips[i];
                if (this._activeTooltipElements.has(t)) {
                    children.push(this._activeTooltipElements.get(t));
                }
                else {
                    if (!TypeRegistrar.isRegistered("IgrTooltipContainer")) {
                        continue;
                    }
                    var Tooltip = TypeRegistrar.get("IgrTooltipContainer");
                    var tEle = React.createElement(Tooltip, {
                        ref: this._tooltipRef,
                        key: this._currentTooltips[i].key,
                        owner: this._currentTooltips[i]
                    });
                    var portal = ReactDOM.createPortal(tEle, t, this._currentTooltips[i].key);
                    this._activeTooltipElements.set(t, portal);
                    children.push(portal);
                }
            }
        }
        var div = React.createElement("div", {
            ref: function (ref) {
                _this._elRef = ref;
            },
            children: children
        });
        return div;
        //}
    };
    IgrDataChart.prototype._tooltipRef = function (t) {
        console.log(t);
        if (t === null) {
            return;
        }
        if (t.currentOwner &&
            t.currentOwner.tooltipTemplate) {
            t.template = t.currentOwner.tooltipTemplate;
        }
        this._activeTooltips.set(t.currentOwner, t);
    };
    IgrDataChart.prototype.componentDidMount = function () {
        _super.prototype.componentDidMount.call(this);
        this._elRef.style.width = this._width ? this._width : "";
        this._elRef.style.height = this._height ? this._height : "";
        this._elRef.appendChild(this._container);
        this._chart.notifyContainerResized();
        this.initializeContent();
    };
    Object.defineProperty(IgrDataChart.prototype, "width", {
        get: function () {
            return this._width;
        },
        set: function (value) {
            this._width = value;
            if (this._elRef) {
                this._elRef.style.height = value;
                this._chart.notifyContainerResized();
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "series", {
        /**
         * A collection or manually added series for the chart.
        */
        get: function () {
            var _this = this;
            if (this._series === null) {
                var coll = new SeriesCollection();
                var inner = coll._innerColl;
                inner.addListener(function (sender, e) {
                    switch (e.action) {
                        case NotifyCollectionChangedAction.Add:
                            _this._seriesAdapter.addManualItem(e.newItems.item(0));
                            break;
                        case NotifyCollectionChangedAction.Remove:
                            _this._seriesAdapter.removeManualItemAt(e.oldStartingIndex);
                            break;
                        case NotifyCollectionChangedAction.Replace:
                            _this._seriesAdapter.removeManualItemAt(e.oldStartingIndex);
                            _this._seriesAdapter.insertManualItem(e.newStartingIndex, e.newItems.item(0));
                            break;
                        case NotifyCollectionChangedAction.Reset:
                            _this._seriesAdapter.clearManualItems();
                            break;
                    }
                });
                this._series = coll;
            }
            return this._series;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "axes", {
        /**
         * A collection or manually added axes for the chart.
        */
        get: function () {
            var _this = this;
            if (this._axes === null) {
                var coll = new AxisCollection();
                var inner = coll._innerColl;
                inner.addListener(function (sender, e) {
                    switch (e.action) {
                        case NotifyCollectionChangedAction.Add:
                            _this._axesAdapter.addManualItem(e.newItems.item(0));
                            break;
                        case NotifyCollectionChangedAction.Remove:
                            _this._axesAdapter.removeManualItemAt(e.oldStartingIndex);
                            break;
                        case NotifyCollectionChangedAction.Replace:
                            _this._axesAdapter.removeManualItemAt(e.oldStartingIndex);
                            _this._axesAdapter.insertManualItem(e.newStartingIndex, e.newItems.item(0));
                            break;
                        case NotifyCollectionChangedAction.Reset:
                            _this._axesAdapter.clearManualItems();
                            break;
                    }
                });
                this._axes = coll;
            }
            return this._axes;
        },
        enumerable: true,
        configurable: true
    });
    IgrDataChart.prototype.componentWillUnmount = function () {
        this._chart.destroy();
        this._wrapper.destroy();
    };
    IgrDataChart.prototype.createImplementation = function () {
        return new XamDataChart();
    };
    Object.defineProperty(IgrDataChart.prototype, "dataSource", {
        get: function () {
            return this._dataSource;
        },
        set: function (value) {
            this._dataSource = value;
            this.bindData();
        },
        enumerable: true,
        configurable: true
    });
    IgrDataChart.prototype.bindData = function () {
        //console.log("binding data: " + this._dataSource);
        if (this.actualAxes && this.actualAxes.length > 0) {
            var currAxes = this.actualAxes;
            for (var i = 0; i < currAxes.length; i++) {
                currAxes[i].provideData(this._dataSource);
            }
        }
        if (this.actualSeries && this.actualSeries.length > 0) {
            var currSeries = this.actualSeries;
            for (var i = 0; i < currSeries.length; i++) {
                currSeries[i].provideData(this._dataSource);
            }
        }
    };
    IgrDataChart.prototype.initializeContent = function () {
        var _this = this;
        if (TypeRegistrar.isRegistered("IgrDataChartDefaultTooltips")) {
            var d = TypeRegistrar.create("IgrDataChartDefaultTooltips");
            this._defaultTooltips = d;
            this._onDefaultTooltipsReady(d);
            //this._container.appendChild(cr.location.nativeElement);
        }
        this._axesAdapter = new CollectionAdapter(this.contentAxes, this.i.axes, this.actualAxes, function (c) { return c.i; }, function (i) { i._provideRenderer(_this._wrapper); i.provideData(_this._dataSource); }, function (i) { i._provideRenderer(null); i.provideData(null); });
        this._seriesAdapter = new CollectionAdapter(this.contentSeries, this.i.series, this.actualSeries, function (c) { return c.i; }, function (i) {
            i.owner = _this;
            i._provideRenderer(_this._dataSource);
            i.provideData(_this._dataSource);
            i.bindAxes(_this.actualAxes);
            _this._ensureDefaultTooltip(i);
            _this._ensureTooltipCreated(i);
        }, function (i) { i._provideRenderer(null); i.provideData(null); });
        this.i.notifyContainerResized();
    };
    IgrDataChart.prototype._ensureTooltipCreated = function (series) {
        var _this = this;
        series._ensureTooltipCreated(function () { return _this.createTooltip(); }, function (ele) {
            var wrapper = new ReactWrapper(ele, _this._wrapper);
            wrapper.updateToolTip = ele.updateToolTip;
            wrapper.hideToolTip = ele.hideToolTip;
            return wrapper;
        });
    };
    IgrDataChart.prototype._ensureDefaultTooltip = function (series) {
        if (this._defaultTooltips == null) {
            return;
        }
        this._defaultTooltips["ensureDefaultTooltip"](series);
    };
    IgrDataChart.prototype._onDefaultTooltipsReady = function (cr) {
        if (this.actualSeries && this.actualSeries.length > 0) {
            var currSeries = this.actualSeries;
            for (var i = 0; i < currSeries.length; i++) {
                if (currSeries[i].showDefaultTooltip) {
                    this._ensureDefaultTooltip(currSeries[i]);
                }
            }
        }
    };
    IgrDataChart.prototype.createTooltip = function () {
        // if (!TypeRegistrar.isRegistered("IgrTooltipContainer")) {
        // 	return null;
        // }
        // let Tooltip = TypeRegistrar.get("IgrTooltipContainer");
        var wrapper = this._wrapper.createElement("div");
        var ele = wrapper.getNativeElement();
        ele.key = "__tooltip_" + this._uniqueTooltipId;
        this._uniqueTooltipId++;
        this._currentTooltips = this._currentTooltips.slice(0);
        this._currentTooltips.push(ele);
        //let element = React.createElement(Tooltip,  );
        //let portal = ReactDOM.createPortal(element, ele);
        var self = this;
        ele.updateToolTip = function (c) {
            if (c.externalObject) {
                c = c.externalObject;
            }
            else {
                var ext = new DataContext();
                ext._implementation = c;
                c = ext;
            }
            if (ele.parentElement != self._container) {
                if (ele.parentElement != null) {
                    ele.parentElement.removeChild(ele);
                }
                self._container.appendChild(ele);
            }
            if (self._activeTooltips.has(ele)) {
                var t = self._activeTooltips.get(ele);
                t.dataContext = c;
            }
            ele.style.display = "block";
            return true;
        };
        ele.hideToolTip = function () {
            ele.style.display = "none";
        };
        ele.style.display = "none";
        this._updateTooltipState();
        return ele;
    };
    IgrDataChart.prototype._updateTooltipState = function () {
        if (this._initialized) {
            this.setState({ tooltips: this._currentTooltips });
        }
    };
    Object.defineProperty(IgrDataChart.prototype, "i", {
        get: function () {
            return this._implementation;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "isSquare", {
        /**
     * Gets or sets whether to use a square aspect ratio for the chart. This is locked to true for polar and radial charts.
    */
        get: function () {
            return this.i.nm;
        },
        set: function (v) {
            this.i.nm = ensureBool(v);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "windowScaleHorizontal", {
        /**
         * A number between 0 and 1 determining the scale of the horizontal zoom.
         * This property is effectively a shortcut to the Width of the WindowRect property.
        */
        get: function () {
            return this.i.n5;
        },
        set: function (v) {
            this.i.n5 = +v;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "windowScaleVertical", {
        /**
         * A number between 0 and 1 determining the scale of the vertical zoom.
         * This property is effectively a shortcut to the Height of the WindowRect property.
        */
        get: function () {
            return this.i.n6;
        },
        set: function (v) {
            this.i.n6 = +v;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "actualWindowScaleHorizontal", {
        /**
         * A number between 0 and 1 determining the scale of the horizontal zoom.
         * This property is effectively a shortcut to the Width of the ActualWindowRect property.
        */
        get: function () {
            return this.i.nx;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "actualWindowScaleVertical", {
        /**
         * A number between 0 and 1 determining the scale of the vertical zoom.
         * This property is effectively a shortcut to the Height of the ActualWindowRect property.
        */
        get: function () {
            return this.i.ny;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "isHorizontalZoomEnabled", {
        /**
         * Gets or sets horizontal zoomability of the current control
        */
        get: function () {
            return this.i.nl;
        },
        set: function (v) {
            this.i.nl = ensureBool(v);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "isVerticalZoomEnabled", {
        /**
         * Gets or sets vertical zoomability of the current control
        */
        get: function () {
            return this.i.nn;
        },
        set: function (v) {
            this.i.nn = ensureBool(v);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "gridMode", {
        /**
         * Gets or sets how grid lines are rendered in relation to series.
        */
        get: function () {
            return this.i.na;
        },
        set: function (v) {
            this.i.na = ensureEnum(GridMode_$type, v);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "alignsGridLinesToPixels", {
        /**
         * Gets or sets a value indicating whether grid and tick lines are aligned to device pixels.
        */
        get: function () {
            return this.i.nh;
        },
        set: function (v) {
            this.i.nh = ensureBool(v);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "brushes", {
        /**
         * Gets or sets the palette of brushes to use for coloring the chart series.
        */
        get: function () {
            return fromBrushCollection(this.i.m3);
        },
        set: function (v) {
            this.i.m3 = toBrushCollection(v);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "markerBrushes", {
        /**
         * Gets or sets the MarkerBrushes property.
         * The brushes property defines the palette from which automatically assigned series brushes are selected.
        */
        get: function () {
            return fromBrushCollection(this.i.m4);
        },
        set: function (v) {
            this.i.m4 = toBrushCollection(v);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "outlines", {
        /**
         * Gets or sets the palette of brushes to use for outlines on the chart series.
        */
        get: function () {
            return fromBrushCollection(this.i.m6);
        },
        set: function (v) {
            this.i.m6 = toBrushCollection(v);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "markerOutlines", {
        /**
         * Gets or sets the MarkerOutlines property.
         * The brushes property defines the palette from which automatically assigned series brushes are selected.
        */
        get: function () {
            return fromBrushCollection(this.i.m5);
        },
        set: function (v) {
            this.i.m5 = toBrushCollection(v);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "defaultAxisStroke", {
        /**
         * Gets or sets the DefaultAxisStroke property.
         * The DefaultAxisStroke property defines the brush which is used by the axes when no Axis.Stroke is set.
        */
        get: function () {
            return brushToString(this.i.pi);
        },
        set: function (v) {
            this.i.pi = stringToBrush(v);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "defaultAxisMajorStroke", {
        /**
         * Gets or sets the DefaultAxisMajorStroke property.
         * The DefaultAxisMajorStroke property defines the brush which is used by the axes when no Axis.MajorStroke is set.
        */
        get: function () {
            return brushToString(this.i.pg);
        },
        set: function (v) {
            this.i.pg = stringToBrush(v);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "defaultAxisMinorStroke", {
        /**
         * Gets or sets the DefaultAxisMinorStroke property.
         * The DefaultAxisMinorStroke property defines the brush which is used by the axes when no Axis.MinorStroke is set.
        */
        get: function () {
            return brushToString(this.i.ph);
        },
        set: function (v) {
            this.i.ph = stringToBrush(v);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "plotAreaMarginLeft", {
        /**
         * Margin applied to the left of the plot area.
        */
        get: function () {
            return this.i.n2;
        },
        set: function (v) {
            this.i.n2 = +v;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "plotAreaMarginTop", {
        /**
         * Margin applied above the plot area.
        */
        get: function () {
            return this.i.n4;
        },
        set: function (v) {
            this.i.n4 = +v;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "plotAreaMarginRight", {
        /**
         * Margin applied to the right of the plot area.
        */
        get: function () {
            return this.i.n3;
        },
        set: function (v) {
            this.i.n3 = +v;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(IgrDataChart.prototype, "plotAreaMarginBottom", {
        /**
         * Margin applied below the plot area.
        */
        get: function () {
            return this.i.n1;
        },
        set: function (v) {
            this.i.n1 = +v;
        },
        enumerable: true,
        configurable: true
    });
    /**
 * Notifies the chart that the CSS styles in effect have been updated.

*/
    IgrDataChart.prototype.styleUpdated = function () {
        this.i.oy();
    };
    /**
     * Export serialized visual data.
    
    */
    IgrDataChart.prototype.exportSerializedVisualData = function () {
        var iv = this.i.og();
        return (iv);
    };
    return IgrDataChart;
}(IgrSeriesViewer));
export { IgrDataChart };
