var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};
import * as shared from './shared/index.js';
import * as appstate from '../appstate.js';
import { DeesElement, customElement, html, state, css, cssManager, } from '@design.estate/dees-element';
let OpsViewLogs = (() => {
    let _classDecorators = [customElement('ops-view-logs')];
    let _classDescriptor;
    let _classExtraInitializers = [];
    let _classThis;
    let _classSuper = DeesElement;
    let _logState_decorators;
    let _logState_initializers = [];
    let _logState_extraInitializers = [];
    var OpsViewLogs = class extends _classSuper {
        static { _classThis = this; }
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _logState_decorators = [state()];
            __esDecorate(this, null, _logState_decorators, { kind: "accessor", name: "logState", static: false, private: false, access: { has: obj => "logState" in obj, get: obj => obj.logState, set: (obj, value) => { obj.logState = value; } }, metadata: _metadata }, _logState_initializers, _logState_extraInitializers);
            __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
            OpsViewLogs = _classThis = _classDescriptor.value;
            if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #logState_accessor_storage = __runInitializers(this, _logState_initializers, {
            recentLogs: [],
            isStreaming: false,
            filters: {},
        });
        get logState() { return this.#logState_accessor_storage; }
        set logState(value) { this.#logState_accessor_storage = value; }
        lastPushedCount = (__runInitializers(this, _logState_extraInitializers), 0);
        constructor() {
            super();
            const subscription = appstate.logStatePart
                .select((stateArg) => stateArg)
                .subscribe((logState) => {
                this.logState = logState;
            });
            this.rxSubscriptions.push(subscription);
        }
        static styles = [
            cssManager.defaultStyles,
            shared.viewHostCss,
            css ``,
        ];
        render() {
            return html `
      <dees-heading level="3">Logs</dees-heading>

      <dees-chart-log
        .label=${'Application Logs'}
        .autoScroll=${true}
        .maxEntries=${2000}
        .showMetrics=${true}
      ></dees-chart-log>
    `;
        }
        async connectedCallback() {
            super.connectedCallback();
            this.lastPushedCount = 0;
            // Only fetch if state is empty (streaming will handle new entries)
            if (this.logState.recentLogs.length === 0) {
                await appstate.logStatePart.dispatchAction(appstate.fetchRecentLogsAction, { limit: 100 });
            }
        }
        async updated(changedProperties) {
            super.updated(changedProperties);
            if (changedProperties.has('logState')) {
                this.pushLogsToChart();
            }
        }
        async pushLogsToChart() {
            const chartLog = this.shadowRoot?.querySelector('dees-chart-log');
            if (!chartLog)
                return;
            // Ensure the chart element has finished its own initialization
            await chartLog.updateComplete;
            // Wait for xterm terminal to finish initializing (CDN load)
            if (!chartLog.terminalReady) {
                await new Promise((resolve) => {
                    let attempts = 0;
                    const maxAttempts = 200; // 200 * 50ms = 10 seconds
                    const check = () => {
                        if (chartLog.terminalReady) {
                            resolve();
                            return;
                        }
                        if (++attempts >= maxAttempts) {
                            console.warn('ops-view-logs: terminal ready timeout after 10s');
                            resolve(); // resolve gracefully to avoid blocking
                            return;
                        }
                        setTimeout(check, 50);
                    };
                    check();
                });
            }
            const allEntries = this.getMappedLogEntries();
            if (this.lastPushedCount === 0 && allEntries.length > 0) {
                // Initial load: push all entries
                chartLog.updateLog(allEntries);
                this.lastPushedCount = allEntries.length;
            }
            else if (allEntries.length > this.lastPushedCount) {
                // Incremental: only push new entries
                const newEntries = allEntries.slice(this.lastPushedCount);
                chartLog.updateLog(newEntries);
                this.lastPushedCount = allEntries.length;
            }
        }
        getMappedLogEntries() {
            return this.logState.recentLogs.map((log) => ({
                timestamp: new Date(log.timestamp).toISOString(),
                level: log.level,
                message: log.message,
                source: log.category,
            }));
        }
        static {
            __runInitializers(_classThis, _classExtraInitializers);
        }
    };
    return OpsViewLogs = _classThis;
})();
export { OpsViewLogs };
//# sourceMappingURL=data:application/json;base64, 