"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseMonitor = void 0;
const events_1 = require("events");
const cache_manager_1 = require("./cache-manager");
const errors_1 = require("../types/errors");
/**
 * 监控订阅实现
 */
class MonitorSubscriptionImpl {
    constructor(callback, interval, monitorFn, errorHandler) {
        this.callback = callback;
        this.interval = interval;
        this.monitorFn = monitorFn;
        this.errorHandler = errorHandler;
        this.active = true;
        this.paused = false;
        this.start();
    }
    unsubscribe() {
        this.stop();
        this.active = false;
    }
    isActive() {
        return this.active;
    }
    pause() {
        if (this.active && !this.paused) {
            this.stop();
            this.paused = true;
        }
    }
    resume() {
        if (this.active && this.paused) {
            this.start();
            this.paused = false;
        }
    }
    getStatus() {
        if (!this.active)
            return 'stopped';
        return this.paused ? 'paused' : 'active';
    }
    start() {
        if (this.timer) {
            clearInterval(this.timer);
        }
        this.timer = setInterval(async () => {
            try {
                const result = await this.monitorFn();
                this.callback(result);
            }
            catch (error) {
                if (this.errorHandler) {
                    this.errorHandler(error);
                }
            }
        }, this.interval);
    }
    stop() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = undefined;
        }
    }
}
/**
 * 基础监控器抽象类
 *
 * 提供所有监控器的通用功能，包括缓存、事件、配置管理等
 */
class BaseMonitor extends events_1.EventEmitter {
    /**
     * 输出首次降级警告（相同 key 仅警告一次）
     * 供适配器和监控器在命令执行失败并降级时调用
     * @param key 降级标识，格式 "{monitor}.{type}"，如 "cpu.command_failed"
     * @param reason 人类可读的降级原因
     */
    static warnDegradation(key, reason) {
        if (!BaseMonitor.warnedDegradations.has(key)) {
            BaseMonitor.warnedDegradations.add(key);
            const monitor = key.split('.')[0];
            console.warn(`[node-os-utils] ${monitor} degraded: ${reason}. Some features may not be available in the current runtime environment.`);
        }
    }
    constructor(adapter, config = {}, cache) {
        super();
        this.subscriptions = new Set();
        this.adapter = adapter;
        this.config = { ...this.getDefaultConfig(), ...config };
        this.cache = cache || new cache_manager_1.CacheManager({
            defaultTTL: this.config.cacheTTL || 5000,
            enabled: this.config.cacheEnabled !== false
        });
        // 设置最大监听器数量
        this.setMaxListeners(100);
    }
    // 通用方法
    /**
     * 配置监控器
     */
    withConfig(config) {
        this.config = { ...this.config, ...config };
        // 如果缓存配置发生变化，更新缓存管理器
        if (config.cacheTTL && this.cache) {
            this.cache.setDefaultTTL(config.cacheTTL);
        }
        return this;
    }
    /**
     * 配置缓存
     */
    withCaching(enabled, ttl) {
        this.config.cacheEnabled = enabled;
        if (ttl !== undefined) {
            this.config.cacheTTL = ttl;
            if (this.cache) {
                this.cache.setDefaultTTL(ttl);
            }
        }
        return this;
    }
    /**
     * 实时监控
     */
    monitor(interval, callback) {
        const monitorFn = async () => {
            const result = await this.info();
            if (result.success) {
                return result.data;
            }
            else {
                throw result.error;
            }
        };
        const errorHandler = (error) => {
            this.emit('error', error);
        };
        const subscription = new MonitorSubscriptionImpl(callback, interval, monitorFn, errorHandler);
        this.subscriptions.add(subscription);
        // 当订阅被取消时，从集合中移除
        const originalUnsubscribe = subscription.unsubscribe.bind(subscription);
        subscription.unsubscribe = () => {
            originalUnsubscribe();
            this.subscriptions.delete(subscription);
        };
        return subscription;
    }
    /**
     * 获取配置
     */
    getConfig() {
        return { ...this.config };
    }
    /**
     * 获取缓存统计
     */
    getCacheStats() {
        return this.cache ? this.cache.getStats() : null;
    }
    /**
     * 清空缓存
     */
    clearCache() {
        if (this.cache) {
            this.cache.clear();
        }
    }
    /**
     * 停止所有监控订阅
     */
    stopAllMonitoring() {
        for (const subscription of this.subscriptions) {
            subscription.unsubscribe();
        }
        this.subscriptions.clear();
    }
    /**
     * 获取活跃订阅数量
     */
    getActiveSubscriptions() {
        return Array.from(this.subscriptions).filter(sub => sub.isActive()).length;
    }
    /**
     * 销毁监控器
     */
    destroy() {
        this.stopAllMonitoring();
        if (this.cache) {
            this.cache.destroy();
        }
        this.removeAllListeners();
    }
    // 受保护的辅助方法
    /**
     * 获取缓存结果
     */
    getCachedResult(key) {
        if (!this.config.cacheEnabled || !this.cache) {
            return undefined;
        }
        return this.cache.get(key);
    }
    /**
     * 设置缓存结果
     */
    setCachedResult(key, result, ttl) {
        if (!this.config.cacheEnabled || !this.cache) {
            return;
        }
        this.cache.set(key, result, ttl);
    }
    /**
     * 创建成功结果
     */
    createSuccessResult(data, cached = false) {
        return {
            success: true,
            data,
            timestamp: Date.now(),
            cached,
            platform: this.adapter.getPlatform()
        };
    }
    /**
     * 创建失败结果
     */
    createErrorResult(error) {
        return {
            success: false,
            error,
            platform: this.adapter.getPlatform(),
            timestamp: Date.now()
        };
    }
    /**
     * 处理错误并转换为 MonitorResult
     */
    handleError(error) {
        let monitorError;
        if (error instanceof errors_1.MonitorError) {
            monitorError = error;
        }
        else if (error instanceof Error) {
            monitorError = new errors_1.MonitorError(error.message, errors_1.ErrorCode.COMMAND_FAILED, this.adapter.getPlatform(), { originalError: error });
        }
        else {
            monitorError = new errors_1.MonitorError('Unknown error occurred', errors_1.ErrorCode.COMMAND_FAILED, this.adapter.getPlatform(), { error });
        }
        // 发射错误事件
        this.emit('error', monitorError);
        return this.createErrorResult(monitorError);
    }
    /**
     * 执行带缓存的操作
     */
    async executeWithCache(cacheKey, operation, ttl) {
        try {
            // 尝试从缓存获取
            const cached = this.getCachedResult(cacheKey);
            if (cached !== undefined) {
                return this.createSuccessResult(cached, true);
            }
            // 执行操作
            const result = await operation();
            // 缓存结果
            this.setCachedResult(cacheKey, result, ttl);
            return this.createSuccessResult(result, false);
        }
        catch (error) {
            return this.handleError(error);
        }
    }
    /**
     * 验证平台支持
     */
    validatePlatformSupport(feature) {
        if (!this.adapter.isSupported(feature)) {
            throw errors_1.MonitorError.createPlatformNotSupported(this.adapter.getPlatform(), feature);
        }
    }
    /**
     * 创建不支持功能的错误
     */
    createUnsupportedError(feature) {
        return errors_1.MonitorError.createPlatformNotSupported(this.adapter.getPlatform(), feature);
    }
    /**
     * 安全执行异步操作
     */
    async safeExecute(operation, fallback) {
        try {
            return await operation();
        }
        catch (error) {
            if (fallback !== undefined) {
                return fallback;
            }
            throw error;
        }
    }
    /**
     * 创建超时 Promise
     */
    createTimeoutPromise(timeoutMs, errorMessage) {
        return new Promise((_, reject) => {
            setTimeout(() => {
                const error = new errors_1.MonitorError(errorMessage || `Operation timed out after ${timeoutMs}ms`, errors_1.ErrorCode.TIMEOUT, this.adapter.getPlatform(), { timeout: timeoutMs });
                reject(error);
            }, timeoutMs);
        });
    }
    /**
     * 带超时执行操作
     */
    async executeWithTimeout(operation, timeoutMs) {
        const timeout = timeoutMs || this.config.timeout || 10000;
        return Promise.race([
            operation(),
            this.createTimeoutPromise(timeout)
        ]);
    }
}
exports.BaseMonitor = BaseMonitor;
/** 已输出过降级警告的 key 集合（进程级别去重） */
BaseMonitor.warnedDegradations = new Set();
//# sourceMappingURL=base-monitor.js.map