/*
 * @Author       : WuWei
 * @LastEditors  : WuWei
 * @Date         : 2021-03-15 10:04:58
 * @LastEditTime : 2021-09-13 15:51:21
 * @FilePath     : /wisdom-huiguanjia-app/app_project/lib/debugHttpOverride.dart
 * @Description  : createHttpClient方法配置自己的ip和自己在抓包软件设置的端口
 */
import 'dart:io';


class MyHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) {
    var httpClient = super.createHttpClient(context);
    
    // 设置代理
    httpClient.findProxy = (uri) {
      if (ProxyManager.isProxyEnabled && ProxyManager.proxyIP != null) {
        return 'PROXY ${ProxyManager.proxyIP}:${ProxyManager.proxyPort}';
      }
      return 'DIRECT';
    };

    // 允许自签名证书（仅用于开发环境）
    httpClient.badCertificateCallback = 
        (X509Certificate cert, String host, int port) => true;
        
    return httpClient;
  }
}

class ProxyManager {
  static String? _proxyIP;
  static int _proxyPort = 52555;
  static bool _isProxyEnabled = false;

  // 获取代理状态
  static bool get isProxyEnabled => _isProxyEnabled;
  static String? get proxyIP => _proxyIP;
  static int get proxyPort => _proxyPort;

  // 初始化代理设置
  static Future<void> initialize() async {
    try {
      // 尝试获取代理IP和端口
      await _detectProxySettings();
      print('Proxy initialized - IP: $_proxyIP, Port: $_proxyPort');
    } catch (e) {
      print('Failed to initialize proxy: $e');
      _isProxyEnabled = false;
    }
  }

  // 检测代理设置
  static Future<void> _detectProxySettings() async {
    try {
      // 获取系统代理设置
      if (Platform.isIOS || Platform.isAndroid) {
        // 移动设备：获取局域网中的代理服务器IP
        _proxyIP = await _getLocalNetworkIP();
      } else {
        // 桌面设备：使用localhost
        _proxyIP = '127.0.0.1';
      }

      // 测试代理连接
      if (_proxyIP != null) {
        final isProxyAvailable = await _testProxyConnection(_proxyIP!, _proxyPort);
        _isProxyEnabled = isProxyAvailable;
      }
    } catch (e) {
      print('Error detecting proxy settings: $e');
      _isProxyEnabled = false;
    }
  }

  // 获取局域网IP地址
  static Future<String?> _getLocalNetworkIP() async {
    try {
      final interfaces = await NetworkInterface.list();
      for (var interface in interfaces) {
        for (var addr in interface.addresses) {
          if (addr.type == InternetAddressType.IPv4) {
            final ip = addr.address;
            if (ip.startsWith('192.168.') || 
                ip.startsWith('10.') ||
                (ip.startsWith('172.') && 
                 int.parse(ip.split('.')[1]) >= 16 && 
                 int.parse(ip.split('.')[1]) <= 31)) {
              
              if (!ip.startsWith('127.')) {
                return ip;
              }
            }
          }
        }
      }
    } catch (e) {
      print('Error getting local network IP: $e');
    }
    return null;
  }

  // 测试代理连接
  static Future<bool> _testProxyConnection(String ip, int port) async {
    try {
      final socket = await Socket.connect(ip, port, 
          timeout: Duration(seconds: 2));
      await socket.close();
      return true;
    } catch (e) {
      print('Proxy connection test failed: $e');
      return false;
    }
  }

  // 更新代理设置
  static Future<void> updateProxySettings() async {
    await _detectProxySettings();
  }
}