/**
 * 连接策略基类
 * 职责：定义所有连接策略的统一接口规范
 * 支持：SSH、K8S Pod、Docker Container 等多种连接类型
 */

// 注意：ConnectionStatus 类型定义与 types.ts 保持一致
export type ConnectionStatus = 'connecting' | 'connected' | 'reconnecting' | 'disconnected' | 'error';

export interface ConnectionConfig {
    type: 'ssh' | 'k8s' | 'docker';
    autoReconnect?: boolean;
    reconnectInterval?: number;
    maxReconnectAttempts?: number;
}

export type StatusChangeCallback = (status: ConnectionStatus) => void;
export type MessageCallback = (data: string) => void;
export type ErrorCallback = (error: string) => void;

/**
 * 抽象连接策略基类
 */
export abstract class BaseConnectionStrategy {
    protected status: ConnectionStatus = 'connecting';  // 初始状态为connecting，符合打开终端时的正常生命周期
    protected statusListeners: Set<StatusChangeCallback> = new Set();
    protected messageListeners: Set<MessageCallback> = new Set();
    protected errorListeners: Set<ErrorCallback> = new Set();

    constructor(protected config: ConnectionConfig) {}

    /**
     * 建立连接
     */
    abstract connect(): Promise<void>;

    /**
     * 断开连接
     */
    abstract disconnect(): void;

    /**
     * 发送输入
     */
    abstract sendInput(data: string): void;

    /**
     * 发送终端尺寸调整消息到后端
     */
    abstract resize(cols: number, rows: number): void;

    /**
     * 获取当前连接状态
     */
    getStatus(): ConnectionStatus {
        return this.status;
    }

    /**
     * 订阅状态变化
     */
    onStatusChange(callback: StatusChangeCallback): () => void {
        this.statusListeners.add(callback);
        return () => this.statusListeners.delete(callback);
    }

    /**
     * 订阅消息接收
     */
    onMessage(callback: MessageCallback): () => void {
        this.messageListeners.add(callback);
        return () => this.messageListeners.delete(callback);
    }

    /**
     * 订阅错误事件
     */
    onError(callback: ErrorCallback): () => void {
        this.errorListeners.add(callback);
        return () => this.errorListeners.delete(callback);
    }

    /**
     * 触发状态变化通知
     */
    protected notifyStatusChange(status: ConnectionStatus): void {
        this.status = status;
        this.statusListeners.forEach(listener => listener(status));
    }

    /**
     * 触发消息接收通知
     */
    protected notifyMessage(data: string): void {
        this.messageListeners.forEach(listener => listener(data));
    }

    /**
     * 触发错误通知
     */
    protected notifyError(error: string): void {
        this.errorListeners.forEach(listener => listener(error));
    }

    /**
     * 清理所有监听器
     */
    protected clearListeners(): void {
        this.statusListeners.clear();
        this.messageListeners.clear();
        this.errorListeners.clear();
    }
}
