import { NetConfig, NetProtocolType } from './NetConfig';

/**
 * 网络配置构建器
 * 提供便捷的方法来创建网络配置
 */
export class NetConfigBuilder {
    private _config: Partial<NetConfig> = {};

    /**
     * 设置服务器地址
     * @param serverUrl 服务器地址
     */
    setServerUrl(serverUrl: string): NetConfigBuilder {
        this._config.serverUrl = serverUrl;
        return this;
    }

    /**
     * 设置协议类型
     * @param protocolType 协议类型
     */
    setProtocolType(protocolType: NetProtocolType): NetConfigBuilder {
        this._config.protocolType = protocolType;
        return this;
    }

    /**
     * 设置为 HTTP 协议
     * @param serverUrl HTTP 服务器地址 (如: https://api.example.com/api)
     */
    useHttp(serverUrl?: string): NetConfigBuilder {
        this._config.protocolType = NetProtocolType.Http;
        if (serverUrl) {
            this._config.serverUrl = serverUrl;
        }
        // HTTP 通常不需要重连
        this._config.autoReconnect = false;
        return this;
    }

    /**
     * 设置为 WebSocket 协议
     * @param serverUrl WebSocket 服务器地址 (如: wss://ws.example.com/api)
     */
    useWebSocket(serverUrl?: string): NetConfigBuilder {
        this._config.protocolType = NetProtocolType.WebSocket;
        if (serverUrl) {
            this._config.serverUrl = serverUrl;
        }
        // WebSocket 默认启用重连
        this._config.autoReconnect = true;
        return this;
    }

    /**
     * 设置超时时间
     * @param timeout 超时时间(毫秒)
     */
    setTimeout(timeout: number): NetConfigBuilder {
        this._config.timeout = timeout;
        return this;
    }

    /**
     * 设置重连配置
     * @param autoReconnect 是否自动重连
     * @param reconnectInterval 重连间隔(毫秒)
     * @param maxReconnectTimes 最大重连次数
     */
    setReconnect(autoReconnect: boolean, reconnectInterval?: number, maxReconnectTimes?: number): NetConfigBuilder {
        this._config.autoReconnect = autoReconnect;
        if (reconnectInterval !== undefined) {
            this._config.reconnectInterval = reconnectInterval;
        }
        if (maxReconnectTimes !== undefined) {
            this._config.maxReconnectTimes = maxReconnectTimes;
        }
        return this;
    }

    /**
     * 设置是否使用JSON格式
     * @param json 是否使用JSON格式
     */
    setJson(json: boolean): NetConfigBuilder {
        this._config.json = json;
        return this;
    }

    /**
     * 构建配置
     */
    build(): NetConfig {
        if (!this._config.serverUrl) {
            throw new Error('Server URL is required');
        }

        return {
            serverUrl: this._config.serverUrl,
            protocolType: this._config.protocolType || NetProtocolType.Http,
            timeout: this._config.timeout || 30000,
            autoReconnect: this._config.autoReconnect ?? true,
            reconnectInterval: this._config.reconnectInterval || 3000,
            maxReconnectTimes: this._config.maxReconnectTimes || 5,
            json: this._config.json ?? true
        };
    }

    /**
     * 创建新的构建器实例
     */
    static create(): NetConfigBuilder {
        return new NetConfigBuilder();
    }
}

/**
 * 预定义的网络配置模板
 */
export class NetConfigTemplates {
    /**
     * 开发环境 HTTP 配置
     */
    static developmentHttp(serverUrl: string): NetConfig {
        return NetConfigBuilder.create()
            .useHttp(serverUrl)
            .setTimeout(10000)
            .build();
    }

    /**
     * 生产环境 HTTP 配置
     */
    static productionHttp(serverUrl: string): NetConfig {
        return NetConfigBuilder.create()
            .useHttp(serverUrl)
            .setTimeout(30000)
            .build();
    }

    /**
     * 开发环境 WebSocket 配置
     */
    static developmentWebSocket(serverUrl: string): NetConfig {
        return NetConfigBuilder.create()
            .useWebSocket(serverUrl)
            .setTimeout(10000)
            .setReconnect(true, 1000, 10) // 更频繁的重连用于开发
            .build();
    }

    /**
     * 生产环境 WebSocket 配置
     */
    static productionWebSocket(serverUrl: string): NetConfig {
        return NetConfigBuilder.create()
            .useWebSocket(serverUrl)
            .setTimeout(30000)
            .setReconnect(true, 3000, 5)
            .build();
    }

    /**
     * 游戏实时对战 WebSocket 配置
     */
    static gameRealtimeWebSocket(serverUrl: string): NetConfig {
        return NetConfigBuilder.create()
            .useWebSocket(serverUrl)
            .setTimeout(5000)  // 短超时
            .setReconnect(true, 500, 20) // 快速重连
            .build();
    }
}

/**
 * 网络环境检测工具
 */
export class NetEnvironmentDetector {
    /**
     * 根据当前环境自动生成配置
     * @param baseUrl 基础URL (不包含协议)
     * @param isProduction 是否为生产环境
     */
    static autoDetect(baseUrl: string, isProduction: boolean = false): {
        http: NetConfig;
        webSocket: NetConfig;
    } {
        const httpUrl = isProduction ? `https://${baseUrl}/api` : `http://${baseUrl}/api`;
        const wsUrl = isProduction ? `wss://${baseUrl}/api` : `ws://${baseUrl}/api`;

        return {
            http: isProduction
                ? NetConfigTemplates.productionHttp(httpUrl)
                : NetConfigTemplates.developmentHttp(httpUrl),
            webSocket: isProduction
                ? NetConfigTemplates.productionWebSocket(wsUrl)
                : NetConfigTemplates.developmentWebSocket(wsUrl)
        };
    }

    /**
     * 检测URL是否为安全连接
     */
    static isSecureUrl(url: string): boolean {
        return url.startsWith('https://') || url.startsWith('wss://');
    }

    /**
     * 转换HTTP URL为WebSocket URL
     */
    static httpToWebSocket(httpUrl: string): string {
        return httpUrl.replace(/^https?:/, httpUrl.startsWith('https:') ? 'wss:' : 'ws:');
    }

    /**
     * 转换WebSocket URL为HTTP URL  
     */
    static webSocketToHttp(wsUrl: string): string {
        return wsUrl.replace(/^wss?:/, wsUrl.startsWith('wss:') ? 'https:' : 'http:');
    }
}