"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Metric = void 0;
const classnames_1 = __importDefault(require("classnames"));
const react_1 = __importStar(require("react"));
const react_redux_1 = require("react-redux");
const redux_1 = require("redux");
const metric_1 = require("./metric");
const text_measurements_1 = require("./text_measurements");
const color_calcs_1 = require("../../../../common/color_calcs");
const color_library_wrappers_1 = require("../../../../common/color_library_wrappers");
const specs_1 = require("../../../../specs");
const chart_1 = require("../../../../state/actions/chart");
const get_accessibility_config_1 = require("../../../../state/selectors/get_accessibility_config");
const get_chart_theme_1 = require("../../../../state/selectors/get_chart_theme");
const get_internal_is_intialized_1 = require("../../../../state/selectors/get_internal_is_intialized");
const get_resolved_background_color_1 = require("../../../../state/selectors/get_resolved_background_color");
const get_settings_spec_1 = require("../../../../state/selectors/get_settings_spec");
const light_theme_1 = require("../../../../utils/themes/light_theme");
const chart_size_1 = require("../../state/selectors/chart_size");
const data_1 = require("../../state/selectors/data");
const has_chart_titles_1 = require("../../state/selectors/has_chart_titles");
function getTextContrastOptions(style) {
    return {
        text: { lightColor: (0, color_library_wrappers_1.colorToRgba)(style.textLightColor), darkColor: (0, color_library_wrappers_1.colorToRgba)(style.textDarkColor) },
        subtitle: {
            lightColor: (0, color_library_wrappers_1.colorToRgba)(style.textSubtitleLightColor),
            darkColor: (0, color_library_wrappers_1.colorToRgba)(style.textSubtitleDarkColor),
        },
        extra: { lightColor: (0, color_library_wrappers_1.colorToRgba)(style.textExtraLightColor), darkColor: (0, color_library_wrappers_1.colorToRgba)(style.textExtraDarkColor) },
    };
}
function Component({ chartId, hasTitles, initialized, size: { width, height }, a11y, specs: [spec], style, backgroundColor, onElementClick, onElementOut, onElementOver, locale, onChartRendered, }) {
    (0, react_1.useEffect)(() => {
        onChartRendered();
    });
    if (!initialized || !spec || width === 0 || height === 0) {
        return null;
    }
    const { data } = spec;
    const totalRows = data.length;
    const maxColumns = data.reduce((acc, row) => Math.max(acc, row.length), 0);
    const panel = { width: width / maxColumns, height: height / totalRows };
    const textContrastOptions = getTextContrastOptions(style);
    const emptyBackgroundRGBA = (0, color_calcs_1.combineColors)((0, color_library_wrappers_1.colorToRgba)(style.emptyBackground), (0, color_library_wrappers_1.colorToRgba)(backgroundColor));
    const emptyBackground = (0, color_library_wrappers_1.RGBATupleToString)(emptyBackgroundRGBA);
    const emptyForegroundColor = (0, color_calcs_1.highContrastColor)(emptyBackgroundRGBA, undefined, textContrastOptions.text).color;
    const metricsConfigs = data.reduce((acc, columns, rowIndex) => {
        acc.configs = acc.configs.concat(columns.map((datum, columnIndex) => {
            const key = `${columnIndex}-${rowIndex}`;
            if (!datum) {
                return {
                    key,
                    type: 'left-empty',
                    className: (0, classnames_1.default)('echMetric', {
                        'echMetric--rightBorder': columnIndex < maxColumns - 1,
                        'echMetric--bottomBorder': rowIndex < totalRows - 1,
                        'echMetric--topBorder': hasTitles && rowIndex === 0,
                    }),
                };
            }
            const textDimensions = (0, text_measurements_1.getMetricTextPartDimensions)(datum, panel, style, locale);
            const totalWidth = panel.width - textDimensions.progressBarWidth - textDimensions.iconGridColumnWidth;
            const valueFontSize = (0, text_measurements_1.getFitValueFontSize)(textDimensions.heightBasedSizes.valueFontSize, totalWidth, textDimensions.visibility.availableHeightWithoutValue, textDimensions.textParts, style.minValueFontSize, datum.valueIcon !== undefined, style.valueFontSize === 'fit', textDimensions.metricSpacing.panelPadding, style.fontFamily);
            acc.fittedValueFontSize = Math.min(acc.fittedValueFontSize, valueFontSize);
            return {
                type: 'metric',
                key,
                datum,
                columnIndex,
                rowIndex,
                textDimensions,
            };
        }), Array.from({ length: maxColumns - columns.length }, (_, zeroBasedColumnIndex) => {
            const columnIndex = zeroBasedColumnIndex + columns.length;
            return {
                key: `missing-${columnIndex}-${rowIndex}`,
                type: 'right-empty',
                className: (0, classnames_1.default)('echMetric', {
                    'echMetric--bottomBorder': rowIndex < totalRows - 1,
                    'echMetric--topBorder': hasTitles && rowIndex === 0,
                }),
            };
        }));
        return acc;
    }, { configs: [], fittedValueFontSize: Number.MAX_SAFE_INTEGER });
    const { valueFontSize, valuePartFontSize } = typeof style.valueFontSize === 'number'
        ? (0, text_measurements_1.getFixedFontSizes)(style.valueFontSize)
        : style.valueFontSize === 'default'
            ? (0, text_measurements_1.getSnappedFontSizes)(metricsConfigs.fittedValueFontSize, panel.height, style)
            : (0, text_measurements_1.getFittedFontSizes)(metricsConfigs.fittedValueFontSize);
    metricsConfigs.configs.forEach((config) => {
        if (config.type === 'metric') {
            config.textDimensions.heightBasedSizes.valueFontSize = valueFontSize;
            config.textDimensions.heightBasedSizes.valuePartFontSize = valuePartFontSize;
        }
    });
    return (react_1.default.createElement("ul", { role: "list", className: "echMetricContainer", "aria-labelledby": a11y.labelId, "aria-describedby": a11y.descriptionId, style: {
            gridTemplateColumns: `repeat(${maxColumns}, minmax(0, 1fr)`,
            gridTemplateRows: `repeat(${totalRows}, minmax(${style.minHeight}px, 1fr)`,
        } }, metricsConfigs.configs.map((config) => {
        return config.type !== 'metric' ? (react_1.default.createElement("li", { key: config.key, role: "presentation" },
            react_1.default.createElement("div", { className: config.className, style: { borderColor: style.border, backgroundColor: emptyBackground } }, config.type === 'left-empty' && (react_1.default.createElement("div", { className: "echMetricEmpty", style: { borderColor: emptyForegroundColor.keyword } }))))) : (react_1.default.createElement("li", { key: config.key },
            react_1.default.createElement(metric_1.Metric, { chartId: chartId, hasTitles: hasTitles, datum: config.datum, totalRows: totalRows, totalColumns: maxColumns, rowIndex: config.rowIndex, columnIndex: config.columnIndex, style: style, backgroundColor: backgroundColor, contrastOptions: textContrastOptions, onElementClick: onElementClick, onElementOut: onElementOut, onElementOver: onElementOver, textDimensions: config.textDimensions })));
    })));
}
Component.displayName = 'Metric';
const mapDispatchToProps = (dispatch) => (0, redux_1.bindActionCreators)({
    onChartRendered: chart_1.onChartRendered,
}, dispatch);
const DEFAULT_PROPS = {
    initialized: false,
    chartId: '',
    hasTitles: false,
    specs: [],
    size: {
        width: 0,
        height: 0,
    },
    a11y: get_accessibility_config_1.DEFAULT_A11Y_SETTINGS,
    style: light_theme_1.LIGHT_THEME.metric,
    backgroundColor: light_theme_1.LIGHT_THEME.background.color,
    locale: specs_1.settingsBuildProps.defaults.locale,
};
const mapStateToProps = (state) => {
    if ((0, get_internal_is_intialized_1.getInternalIsInitializedSelector)(state) !== get_internal_is_intialized_1.InitStatus.Initialized) {
        return DEFAULT_PROPS;
    }
    const { onElementClick, onElementOut, onElementOver, locale } = (0, get_settings_spec_1.getSettingsSpecSelector)(state);
    const { metric: style } = (0, get_chart_theme_1.getChartThemeSelector)(state);
    return {
        initialized: true,
        chartId: state.chartId,
        hasTitles: (0, has_chart_titles_1.hasChartTitles)(state),
        specs: (0, data_1.getMetricSpecs)(state),
        size: (0, chart_size_1.chartSize)(state),
        a11y: (0, get_accessibility_config_1.getA11ySettingsSelector)(state),
        onElementClick,
        onElementOver,
        onElementOut,
        backgroundColor: (0, get_resolved_background_color_1.getResolvedBackgroundColorSelector)(state),
        style,
        locale,
    };
};
exports.Metric = (0, react_redux_1.connect)(mapStateToProps, mapDispatchToProps)(Component);
//# sourceMappingURL=index.js.map