var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
import { useLayoutEffect, useRef, useState } from 'react';
var WIDTH_DEFAULT = 60;
var WIDTH_MAX = 100;
var canvas = document === null || document === void 0 ? void 0 : document.createElement('canvas');
var context = canvas === null || canvas === void 0 ? void 0 : canvas.getContext('2d');
var propsDefault = {
    chartYAxisProps: { tickFormatter: function (value) { return String(value); }, width: WIDTH_DEFAULT },
    modifyWidth: function (width) { return width; }
};
export var useDynamicYAxisWidth = function (_a) {
    var _b = _a === void 0 ? propsDefault : _a, _c = _b.chartYAxisProps, _d = _c === void 0 ? propsDefault.chartYAxisProps : _c, _e = _d.tickFormatter, tickFormatter = _e === void 0 ? propsDefault.chartYAxisProps.tickFormatter : _e, _f = _d.width, fixedWidth = _f === void 0 ? propsDefault.chartYAxisProps.width : _f, _g = _b.modifyWidth, modifyWidth = _g === void 0 ? propsDefault.modifyWidth : _g, effectDependencies = _b.effectDependencies;
    var chartRef = useRef(null);
    var _h = useState(fixedWidth), width = _h[0], setWidth = _h[1];
    var formattedTicks = new Set();
    var tickFormatterWithCollector = function (value, index) {
        var formattedTick = tickFormatter(value, index);
        formattedTicks.add(formattedTick);
        return formattedTick;
    };
    useLayoutEffect(function () {
        var _a;
        if (window && context && ((_a = chartRef.current) === null || _a === void 0 ? void 0 : _a.container)) {
            context.font = window.getComputedStyle(chartRef.current.container, null).getPropertyValue('font');
            var maxTickWidth = Math.max.apply(Math, __spreadArray([0], Array.from(formattedTicks).map(function (formattedTick) { return context.measureText(formattedTick).width; }), false));
            if (maxTickWidth) {
                var newWidth = modifyWidth(Math.min(Math.ceil(maxTickWidth) + 2, WIDTH_MAX));
                if (newWidth !== width) {
                    setWidth(newWidth);
                }
            }
        }
    }, effectDependencies); // eslint-disable-line react-hooks/exhaustive-deps
    return { width: width, tickFormatter: tickFormatterWithCollector, chartRef: chartRef };
};
