'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _tslib = require('../chunks/bundle-9l41IWgC.js');
var React = require('react');
var index = require('../chunks/bundle-Gw-7KmmG.js');
var ui_MessageTemplate = require('../chunks/bundle-csbD2FCX.js');
var useSendbirdStateContext = require('../useSendbirdStateContext.js');
var ui_FallbackTemplateMessageItemBody_tsx = require('./FallbackTemplateMessageItemBody.tsx.js');
var ui_LoadingTemplateMessageItemBody_tsx = require('./LoadingTemplateMessageItemBody.tsx.js');
require('@sendbird/chat/groupChannel');
require('../utils/message/getOutgoingMessageState.js');
require('../chunks/bundle-SWOq3kxG.js');
require('../withSendbird.js');
require('../chunks/bundle-2dTv415Y.js');
require('../chunks/bundle-xtUT3duD.js');
require('../chunks/bundle-qYN98FNj.js');
require('../chunks/bundle-5i9-ntZ5.js');
require('./Loader.js');
require('./Icon.js');
require('../chunks/bundle-BdWL3kB4.js');

var MessageTemplateWrapper = function (_a) {
    var message = _a.message, templateItems = _a.templateItems;
    return React.createElement(ui_MessageTemplate.MessageProvider, { message: message },
        React.createElement(ui_MessageTemplate.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: _tslib.__assign(_tslib.__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.createElement(ui_FallbackTemplateMessageItemBody_tsx.FallbackTemplateMessageItemBody, { className: className, message: message, isByMe: isByMe });
    }
    var templateKey = templateData.key;
    var globalState = useSendbirdStateContext.useSendbirdStateContext();
    if (!globalState) {
        return React.createElement(ui_FallbackTemplateMessageItemBody_tsx.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 = React.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 = React.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(',');
    React.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.createElement(ui_FallbackTemplateMessageItemBody_tsx.FallbackTemplateMessageItemBody, { className: className, message: message, isByMe: isByMe });
        }
        return React.createElement(ui_LoadingTemplateMessageItemBody_tsx.LoadingTemplateMessageItemBody, { className: className, isByMe: isByMe });
    }
    return (React.createElement("div", { className: index.getClassName([
            className,
            isByMe ? 'outgoing' : 'incoming',
            'sendbird-template-message-item-body',
        ]) },
        React.createElement(MessageTemplateWrapper, { message: message, templateItems: filledMessageTemplateItems })));
}

exports.TemplateMessageItemBody = TemplateMessageItemBody;
exports.default = TemplateMessageItemBody;
//# sourceMappingURL=TemplateMessageItemBody.js.map
