import { _ as __assign } from '../chunks/bundle-KIf79auh.js';
import React__default, { useState, useEffect } from 'react';
import { w as getClassName } from '../chunks/bundle-LTiCF37t.js';
import { M as MessageProvider, a as MessageTemplate } from '../chunks/bundle-6KFri-1A.js';
import { useSendbirdStateContext } from '../useSendbirdStateContext.js';
import { FallbackTemplateMessageItemBody } from './FallbackTemplateMessageItemBody.tsx.js';
import { LoadingTemplateMessageItemBody } from './LoadingTemplateMessageItemBody.tsx.js';
import '@sendbird/chat/groupChannel';
import '../utils/message/getOutgoingMessageState.js';
import '../chunks/bundle-0QDb7-Y_.js';
import '../withSendbird.js';
import '../chunks/bundle-wpc1Fted.js';
import '../chunks/bundle-XDy3Cf54.js';
import '../chunks/bundle-wWnN6K3w.js';
import '../chunks/bundle-9c5vLDe9.js';
import './Loader.js';
import './Icon.js';
import '../chunks/bundle-DHw1C5gJ.js';

var MessageTemplateWrapper = function (_a) {
    var message = _a.message, templateItems = _a.templateItems;
    return React__default.createElement(MessageProvider, { message: message },
        React__default.createElement(MessageTemplate, { templateItems: templateItems }));
};

var NumberValueKeys = [
    'version',
    'size',
    'top',
    'left',
    'right',
    'bottom',
    'maxTextLines',
    'value',
    'pixelWidth',
    'pixelHeight',
    'radius',
];
function restoreNumbersFromMessageTemplateObject(value, key) {
    if (Array.isArray(value)) {
        return value.map(function (item) { return restoreNumbersFromMessageTemplateObject(item); });
    }
    if (typeof value === 'object') {
        return Object.keys(value).reduce(function (acc, key) {
            acc[key] = restoreNumbersFromMessageTemplateObject(value[key], key);
            return acc;
        }, {});
    }
    if (key != null && NumberValueKeys.includes(key)) {
        var numberValue = Number(value);
        return Number.isNaN(numberValue) ? value : numberValue;
    }
    return value;
}

var flattenObjectHelper = function (currentObject, flattenObject, parentKeyPath) {
    if (parentKeyPath === void 0) { parentKeyPath = ''; }
    for (var _i = 0, _a = Object.entries(currentObject); _i < _a.length; _i++) {
        var _b = _a[_i], key = _b[0], value = _b[1];
        var currentKeyPath = parentKeyPath ? "".concat(parentKeyPath, ".").concat(key) : key;
        if (value && typeof value === 'object') {
            flattenObjectHelper(value, flattenObject, currentKeyPath);
        }
        else {
            flattenObject[currentKeyPath] = value;
        }
    }
};
/**
 * Returns flattened object.
 * ex.
 * given { key-1: { key-1.1: 'value-1.1' }, key-2: 'value-2' }
 * returns { key-1.key-1.1: 'value-1.1', key-2: 'value-2' }
 */
function flattenObject(object) {
    var result = {};
    flattenObjectHelper(object, result);
    return result;
}

function mapData(_a) {
    var template = _a.template, source = _a.source;
    if (!['object', 'string'].includes(typeof template) || !template)
        return template;
    var regex = /\{([^}]+)\}/g;
    var flattenedSource = flattenObject(source);
    function replaceVariablePlaceholder(value) {
        return typeof value === 'string'
            ? value.replace(regex, function (_, placeholder) {
                var value = flattenedSource[placeholder];
                return value || "{".concat(placeholder, "}");
            })
            : mapData({ template: value, source: source });
    }
    if (typeof template === 'string') {
        return replaceVariablePlaceholder(template);
    }
    if (Array.isArray(template)) {
        return template.map(replaceVariablePlaceholder);
    }
    var result = {};
    for (var key in template) {
        if (Object.prototype.hasOwnProperty.call(template, key)) {
            var value = template[key];
            result[key] = replaceVariablePlaceholder(value);
        }
    }
    return result;
}

function convertArgbToRgba(string) {
    if (!string.startsWith('#')) {
        return string;
    }
    if (string.length === 9) {
        return "#".concat(string.slice(3)).concat(string[1]).concat(string[2]);
    }
    if (string.length === 5) {
        return "#".concat(string.slice(2)).concat(string[1]);
    }
    return string;
}
var splitColorVariables = function (colorVariables) {
    var light = {};
    var dark = {};
    for (var key in colorVariables) {
        if (Object.prototype.hasOwnProperty.call(colorVariables, key)) {
            var value = colorVariables[key];
            if (typeof value === 'object' && value !== null) {
                var _a = splitColorVariables(value), nestedLight = _a[0], nestedDark = _a[1];
                light[key] = nestedLight;
                dark[key] = nestedDark;
            }
            else if (typeof value === 'string') {
                var _b = value.split(','), lightColor = _b[0], darkColor = _b[1];
                light[key] = convertArgbToRgba(lightColor);
                dark[key] = convertArgbToRgba(darkColor || lightColor); // when dark color is not provided, use light color
            }
            else {
                light[key] = value;
                dark[key] = value;
            }
        }
    }
    return [light, dark];
};
function selectColorVariablesByTheme(_a) {
    var colorVariables = _a.colorVariables, theme = _a.theme;
    var _b = splitColorVariables(colorVariables), light = _b[0], dark = _b[1];
    return theme === 'light' ? light : dark;
}

var TEMPLATE_FETCH_RETRY_BUFFER_TIME_IN_MILLIES = 500; // It takes about 450ms for isError update
/**
 * Returns copied message template object filled with given template data and color variables.
 */
var getFilledMessageTemplateWithData = function (template, templateData, colorVariables, theme) {
    var selectedThemeColorVariables = selectColorVariablesByTheme({
        colorVariables: colorVariables,
        theme: theme,
    });
    var parsedTemplate = mapData({
        template: restoreNumbersFromMessageTemplateObject(template),
        source: __assign(__assign({}, templateData), selectedThemeColorVariables),
    });
    return parsedTemplate;
};
function TemplateMessageItemBody(_a) {
    var _b;
    var _c = _a.className, className = _c === void 0 ? '' : _c, message = _a.message, _d = _a.isByMe, isByMe = _d === void 0 ? false : _d, _e = _a.theme, theme = _e === void 0 ? 'light' : _e;
    var templateData = (_b = message.extendedMessagePayload) === null || _b === void 0 ? void 0 : _b['template'];
    if (!(templateData === null || templateData === void 0 ? void 0 : templateData.key)) {
        return React__default.createElement(FallbackTemplateMessageItemBody, { className: className, message: message, isByMe: isByMe });
    }
    var templateKey = templateData.key;
    var globalState = useSendbirdStateContext();
    if (!globalState) {
        return React__default.createElement(FallbackTemplateMessageItemBody, { className: className, message: message, isByMe: isByMe });
    }
    var _f = globalState.utils, getCachedTemplate = _f.getCachedTemplate, updateMessageTemplatesInfo = _f.updateMessageTemplatesInfo;
    var waitingTemplateKeysMap = globalState.stores.appInfoStore.waitingTemplateKeysMap;
    var _g = useState(function () {
        var _a;
        var cachedTemplate = getCachedTemplate(templateData.key);
        if (cachedTemplate) {
            return getFilledMessageTemplateWithData(JSON.parse(cachedTemplate.uiTemplate), (_a = templateData.variables) !== null && _a !== void 0 ? _a : {}, cachedTemplate.colorVariables, theme);
        }
        else {
            return [];
        }
    }), filledMessageTemplateItems = _g[0], setFilledMessageTemplateItems = _g[1];
    var _h = useState(false), isErrored = _h[0], setIsErrored = _h[1];
    var waitingTemplateKeysMapString = Object.entries(waitingTemplateKeysMap)
        .map(function (_a) {
        var key = _a[0], value = _a[1];
        return [key, value.requestedAt, value.isError].join('-');
    }).join(',');
    useEffect(function () {
        var _a;
        // Do not put && !isErrored here in case where errored key is fetched in the future by future message
        if (filledMessageTemplateItems.length === 0) {
            var cachedTemplate = getCachedTemplate(templateKey);
            if (cachedTemplate) {
                var filledMessageTemplateItems_1 = getFilledMessageTemplateWithData(JSON.parse(cachedTemplate.uiTemplate), (_a = templateData.variables) !== null && _a !== void 0 ? _a : {}, cachedTemplate.colorVariables, theme);
                setFilledMessageTemplateItems(filledMessageTemplateItems_1);
            }
            else if (!isErrored) { // This prevents duplicate GET calls by already errored message when a new message with same key is calling GET
                /**
                 * Attempt GET template by key IFF one of below cases is met:
                 * 1. This is the first GET call for the template key.
                 * 2. Minimum buffer time has passed since the previous GET error.
                 */
                var waitingTemplateKeyData = waitingTemplateKeysMap[templateKey];
                var requestedAt = Date.now();
                if (!waitingTemplateKeyData
                    || (requestedAt > waitingTemplateKeyData.requestedAt + TEMPLATE_FETCH_RETRY_BUFFER_TIME_IN_MILLIES)) {
                    updateMessageTemplatesInfo(templateData.key, Date.now());
                }
                else if (waitingTemplateKeyData && waitingTemplateKeyData.isError) {
                    setIsErrored(true);
                }
            }
        }
    }, [templateData.key, waitingTemplateKeysMapString]);
    if (filledMessageTemplateItems.length === 0) {
        if (isErrored) {
            return React__default.createElement(FallbackTemplateMessageItemBody, { className: className, message: message, isByMe: isByMe });
        }
        return React__default.createElement(LoadingTemplateMessageItemBody, { className: className, isByMe: isByMe });
    }
    return (React__default.createElement("div", { className: getClassName([
            className,
            isByMe ? 'outgoing' : 'incoming',
            'sendbird-template-message-item-body',
        ]) },
        React__default.createElement(MessageTemplateWrapper, { message: message, templateItems: filledMessageTemplateItems })));
}

export { TemplateMessageItemBody, TemplateMessageItemBody as default };
//# sourceMappingURL=TemplateMessageItemBody.js.map
