"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.LogGroups = void 0;
const react_1 = __importStar(require("react"));
const icons_1 = require("../../icons");
const inlines_1 = require("inlines");
const components_1 = require("../../components");
const varsUtilities_1 = require("../../varsUtilities");
const dayjs_1 = __importDefault(require("dayjs"));
const VerticalLine = (0, inlines_1.styled)('div', {
    height: '100%',
    width: '1px',
    backgroundColor: (0, varsUtilities_1.color)('border', 'default'),
    position: 'absolute',
    left: 12,
    top: 0,
    bottom: 0,
    zIndex: 0,
});
const StatusDotBorder = (0, inlines_1.styled)('div', {
    height: 24,
    width: 24,
    borderRadius: 24,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: (0, varsUtilities_1.color)('background', 'negative', 'subtle'),
});
const StatusDot = (0, inlines_1.styled)('div', {
    height: 14,
    width: 14,
    borderRadius: 24,
    backgroundColor: (0, varsUtilities_1.color)('background', 'inverted', 'surface'),
});
// groupby -> groupbytime, type, status,
// if within time and is same type... group m
// TODO: Scroll direction bottom to top, top to bottom
// TODO: counter for logs per block.
const orderBy = (arr, props, orders) => [...arr].sort((a, b) => props.reduce((acc, prop, i) => {
    if (acc === 0) {
        const [p1, p2] = orders && orders[i] === 'desc'
            ? [b[prop], a[prop]]
            : [a[prop], b[prop]];
        acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0;
    }
    return acc;
}, 0));
const LogGroups = ({ data, groupByTime }) => {
    const groupByTimeInMilliSeconds = groupByTime * 60000;
    const orderedByTypeAndTime = orderBy(data, ['type', 'ts'], ['desc', 'desc']);
    const checkIfThereAreSameTypeAndWithinRange = (obj, obj2) => {
        const tsResult = Math.abs(obj.ts - obj2?.ts);
        if (obj.type === obj2?.type &&
            obj.subType === obj2?.subType &&
            tsResult < groupByTimeInMilliSeconds) {
            return true;
        }
    };
    const pairs = [];
    for (let i = 0; i < orderedByTypeAndTime.length; i++) {
        if (checkIfThereAreSameTypeAndWithinRange(orderedByTypeAndTime[i], orderedByTypeAndTime[i + 1])) {
            pairs.push([i, i + 1]);
        }
        else {
            pairs.push([i, i]);
        }
    }
    //todo nice types
    const result = [];
    let item;
    for (let i = 0; i < pairs.length; i++) {
        const arr = pairs[i];
        if (!item) {
            item = arr;
            result.push(item);
        }
        const next = pairs[i + 1];
        if (next && item[1] === next[0]) {
            item[1] = next[1];
        }
        else {
            item = null;
        }
    }
    const finalArr = [];
    for (let i = 0; i < result.length; i++) {
        finalArr.splice(result[i][0], result[i][1] + 1);
        finalArr.push(orderedByTypeAndTime.slice(result[i][0], result[i][1] + 1));
    }
    const finalOrderBy = (arr, props, orders) => [...arr].sort((a, b) => props.reduce((acc, prop, i) => {
        if (acc === 0) {
            const [p1, p2] = orders && orders[i] === 'desc'
                ? [b[0][prop], a[0][prop]]
                : [a[0][prop], b[0][prop]];
            acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0;
        }
        return acc;
    }, 0));
    const finalFinalOrderedArr = finalOrderBy(finalArr, ['ts'], ['desc']);
    return (react_1.default.createElement(inlines_1.styled.div, { style: { width: '100%' } }, finalFinalOrderedArr.map((item, idx) => {
        return (react_1.default.createElement(GroupedLogs, { key: idx, color: item[0].color, ts: item[0].ts, msg: item[0].msg, type: item[0].type, status: item[0]?.status, subType: item[0]?.subType, subItems: item }));
    })));
};
exports.LogGroups = LogGroups;
const GroupedLogs = ({ ts, msg, color, type, status, subType, subItems }) => {
    const [expanded, setExpanded] = (0, react_1.useState)(false);
    // Scroll logic
    const [isAtBottom, setIsAtBottom] = (0, react_1.useState)(true);
    const ref = (0, react_1.useRef)();
    const scrollHandler = (e) => {
        const { scrollTop, scrollHeight, clientHeight } = e.target;
        const newIsAtBottom = scrollTop + clientHeight >= scrollHeight;
        setIsAtBottom(newIsAtBottom);
    };
    (0, react_1.useEffect)(() => {
        if (ref.current) {
            ref.current.addEventListener('scroll', scrollHandler);
        }
        return () => {
            if (ref.current) {
                ref.current.removeEventListener('scroll', scrollHandler);
            }
        };
    }, [ref]);
    return (react_1.default.createElement(inlines_1.styled.div, { style: { display: 'flex', position: 'relative' } },
        react_1.default.createElement(VerticalLine, null),
        react_1.default.createElement(inlines_1.styled.div, { style: {
                display: 'flex',
                backgroundColor: (0, varsUtilities_1.color)('background', 'default', 'surface'),
                alignItems: 'center',
                justifyContent: 'center',
                width: 32,
                height: 32,
                zIndex: 1,
                position: 'relative',
                marginLeft: -4,
                marginTop: 4,
            } },
            react_1.default.createElement(StatusDotBorder, { style: {
                    backgroundColor: (0, varsUtilities_1.color)('background', color, 'subtle') ??
                        (status === 'error'
                            ? (0, varsUtilities_1.color)('background', 'negative', 'subtle')
                            : status === 'succes'
                                ? (0, varsUtilities_1.color)('background', 'positive', 'subtle')
                                : status === 'info'
                                    ? (0, varsUtilities_1.color)('background', 'informative', 'subtle')
                                    : (0, varsUtilities_1.color)('background', 'inverted', 'subtle')),
                } },
                react_1.default.createElement(StatusDot, { style: {
                        backgroundColor: (0, varsUtilities_1.color)('background', color, 'subtle') ??
                            (status === 'error'
                                ? (0, varsUtilities_1.color)('background', 'negative', 'subtle')
                                : status === 'succes'
                                    ? (0, varsUtilities_1.color)('background', 'positive', 'subtle')
                                    : status === 'info'
                                        ? (0, varsUtilities_1.color)('background', 'informative', 'subtle')
                                        : (0, varsUtilities_1.color)('background', 'inverted', 'subtle')),
                    } }))),
        react_1.default.createElement("div", { style: { marginBottom: 20, width: '100%' } },
            react_1.default.createElement(inlines_1.styled.div, { style: {
                    borderRadius: 8,
                    padding: '12px 6px',
                    width: '100%',
                    // '&:hover': {
                    //   backgroundColor: '#eeeffd7d',
                    // },
                }, onClick: () => setExpanded(!expanded) },
                react_1.default.createElement(GroupedLogsHeader, { ts: ts, color: color, type: type, status: status, subType: subType, msg: msg }),
                expanded && (react_1.default.createElement(inlines_1.styled.div, { ref: ref, style: {
                        maxWidth: '100%',
                        '&::-webkit-scrollbar': {
                            backgroundColor: 'rgba(0,0,0,0)',
                            width: '8px',
                        },
                        '&::-webkit-scrollbar-thumb': {
                            backgroundColor: (0, varsUtilities_1.color)('background', 'default', 'surface'),
                            borderRadius: '12px',
                        },
                    } },
                    msg.length || msg.includes('\n') > 74 ? (react_1.default.createElement(SingleLog, { msg: msg, style: { marginTop: 16 } })) : null,
                    react_1.default.createElement(components_1.ScrollArea, null, subItems.map((item, idx) => idx !== 0 ? (react_1.default.createElement(SingleLog, { msg: item.msg, key: idx, ts: item.ts, type: item.type, idx: idx })) : null)))),
                !expanded && subItems.length > 1 ? (react_1.default.createElement(inlines_1.styled.div, { style: {
                        display: 'flex',
                        alignItems: 'center',
                        marginTop: 4,
                        marginLeft: 8,
                        cursor: 'pointer',
                        '& svg': {
                            '& path': {
                                strokeWidth: 3,
                            },
                        },
                    } },
                    react_1.default.createElement(icons_1.IconChevronDown, { color: "default", style: { marginRight: 8 } }),
                    react_1.default.createElement(components_1.Text, { color: "default", light: true, weight: "strong" },
                        "Show ",
                        subItems.length - 1,
                        " more logs"))) : null))));
};
const GroupedLogsHeader = ({ ts, color, type, status, subType, msg }) => {
    return (react_1.default.createElement(inlines_1.styled.div, null,
        react_1.default.createElement(inlines_1.styled.div, { style: { display: 'flex', marginBottom: 4 } },
            react_1.default.createElement(inlines_1.styled.div, { style: {
                    display: 'flex',
                    alignItems: 'center',
                } },
                react_1.default.createElement(inlines_1.styled.div, { style: {
                        display: 'flex',
                        backgroundColor: (0, varsUtilities_1.color)('background', 'inverted', 'surface'),
                        padding: '2px 8px',
                        borderRadius: type ? ' 12px 0px 0px 12px' : '12px',
                        borderRight: `1px solid ${(0, varsUtilities_1.color)('border', 'default')}`,
                    } },
                    react_1.default.createElement(components_1.Text, null,
                        (0, dayjs_1.default)(ts).format('HH:mm:ss'),
                        " "),
                    react_1.default.createElement(components_1.Text, { light: true, style: { marginLeft: 4 } }, (0, dayjs_1.default)(ts).format('DD/MM/YYYY'))),
                type ? (react_1.default.createElement(inlines_1.styled.div, { style: {
                        border: '1px solid red',
                        display: 'flex',
                        backgroundColor: (0, varsUtilities_1.color)('background', 'inverted', 'surface'),
                        padding: '2px 8px',
                        borderRadius: ' 0px 12px 12px 0px',
                    } },
                    react_1.default.createElement(components_1.Text, null, type))) : null)),
        msg[0] === '{' ? (react_1.default.createElement("pre", { style: {
                color: (0, varsUtilities_1.color)('content', 'default', 'secondary'),
                boxSizing: 'inherit',
                display: 'inherit',
                userSelect: 'text',
                padding: 0,
                margin: 0,
                marginLeft: 8,
                marginTop: 8,
                border: undefined,
                lineHeight: '18px',
                fontSize: 14,
                fontFamily: 'Fira Code',
                wordBreak: 'break-all',
                whiteSpace: 'break-spaces',
                overflowWrap: 'break-word',
                position: 'relative',
            }, dangerouslySetInnerHTML: { __html: msg } })) : (react_1.default.createElement(components_1.Text, { style: {
                marginBottom: 12,
                marginTop: 8,
                marginLeft: 8,
                cursor: 'pointer',
            }, light: true, color: status === 'error' ? 'negative' : 'default' }, msg.split('\n')[0].substring(0, 74))),
        subType ? (react_1.default.createElement(inlines_1.styled.div, { style: { marginBottom: 8 } }, typeof subType === 'string' ? react_1.default.createElement(components_1.Text, { light: true }, subType) : subType)) : null));
};
const SingleLog = ({ msg, style, ts, type, idx }) => {
    return (react_1.default.createElement(inlines_1.styled.div, { style: {
            background: (0, varsUtilities_1.color)('background', 'default', 'surface'),
            marginBottom: 8,
            ...style,
        }, onClick: (e) => {
            e.stopPropagation();
        } },
        idx === 0 && ts && (react_1.default.createElement(inlines_1.styled.div, { style: { display: 'flex' } },
            react_1.default.createElement(inlines_1.styled.div, { style: {
                    display: 'flex',
                    background: (0, varsUtilities_1.color)('background', 'inverted', 'surface'),
                    padding: '2px 8px',
                    borderRadius: ' 12px 0px 0px 12px',
                    borderRight: `1px solid ${(0, varsUtilities_1.color)('border', 'default')}`,
                } },
                react_1.default.createElement(components_1.Text, null,
                    (0, dayjs_1.default)(ts).format('HH:mm:ss'),
                    " "),
                react_1.default.createElement(components_1.Text, { light: true, style: { marginLeft: 4 } }, (0, dayjs_1.default)(ts).format('DD/MM/YYYY'))),
            react_1.default.createElement(inlines_1.styled.div, { style: {
                    display: 'flex',
                    background: (0, varsUtilities_1.color)('background', 'inverted', 'surface'),
                    padding: '2px 8px',
                    borderRadius: ' 0px 12px 12px 0px',
                } },
                react_1.default.createElement(components_1.Text, null, type)))),
        idx !== 0 && msg[0] !== '{' && (react_1.default.createElement("pre", { style: {
                color: (0, varsUtilities_1.color)('content', 'default', 'secondary'),
                boxSizing: 'inherit',
                display: 'inherit',
                userSelect: 'text',
                padding: 0,
                margin: 0,
                marginLeft: 8,
                marginTop: 10,
                border: undefined,
                lineHeight: '18px',
                fontSize: 14,
                fontFamily: 'Fira Code',
                wordBreak: 'break-all',
                whiteSpace: 'break-spaces',
                overflowWrap: 'break-word',
                position: 'relative',
            } }, msg))));
};
//# sourceMappingURL=LogGroups.js.map