import 'dart:async';
import 'dart:io';
import 'package:get/get.dart';
import 'package:naiyouwl/app/common/LogHelper.dart';
import 'package:naiyouwl/app/controller/controllers.dart';
import 'package:naiyouwl/app/component/connection_status.dart';
import 'package:naiyouwl/app/clash/service/clash_service.dart';
import 'package:naiyouwl/app/controller/service.dart';
import 'package:naiyouwl/app/utils/shell.dart';
import 'package:wl_base_help/wl_base_help.dart';

import '../controller/GlobalController.dart';
import '../modules/home/controllers/home_controller.dart';
import '../utils/WindowsProxyManager.dart';
import '../utils/utils.dart';

class ConnectionService {
  final GlobalController globalController;
  final Function(ConnectionStatus) updateStatus;
  final ClashService clashService = Get.find<ClashService>();
  final ServiceController serviceController = Get.find<ServiceController>();

  ConnectionService(this.globalController, this.updateStatus);
  Future<void> startConnectionMac() async {
    updateStatus(ConnectionStatus.connecting);
    globalController.updateMsg("正在启动连接...");
    await globalController.updateNode();
    await globalController.swift(globalController.selectedNode.value?.name ?? "");
    // 等待连接建立
    await Future.delayed(Duration(seconds: 2));
    updateStatus(ConnectionStatus.connected);
    globalController.connectStatus.value = true;
    globalController.updateMsg("连接成功");
    await globalController.openProxy();
  }

  Future<void> startConnectionWin() async {
    try {
      updateStatus(ConnectionStatus.connecting);
      globalController.updateMsg("正在启动连接...");
      await globalController.updateNode();
      await globalController.swift(globalController.selectedNode.value?.name ?? "");
      // 等待连接建立
      await Future.delayed(Duration(seconds: 2));
      updateStatus(ConnectionStatus.connected);
      globalController.connectStatus.value = true;
      globalController.updateMsg("连接成功");

      final proxyManager = WlBaseHelp();

      if(Platform.isWindows){
        int? port = controllers.config.mixedPort.value;
        if (port == 0) {
          port = null;
        }
        int? socksPort = controllers.config.mixedPort.value;
        if (socksPort == 0) {
          socksPort = null;
        }
        int? mixedPort = controllers.config.mixedPort.value;
        if (mixedPort == 0) {
          mixedPort = null;
        }

        if(port !=null){
          await proxyManager.startProxy(port);
        }

      }

      // // 检查所有内核是否已停止
      // bool allCoresStopped = await globalController.checkAllCoresStopped();
      //
      // if (!allCoresStopped) {
      //   // 检查并停止占用端口
      //   await globalController.checkAndStopIfPortsOccupied();
      //
      //   // 如果端口被占用,尝试更换端口
      //   if (globalController.msgStatus.value == '端口被占用,已停止所有内核') {
      //     // 尝试为每个端口找到新的可用端口
      //     int newMixedPort = await findAvailablePort(controllers.config.mixedPort.value);
      //     int newApiPort = await findAvailablePort(controllers.config.apiAddressPort.value);
      //     int newServicePort = await findAvailablePort(controllers.config.servicePort.value);
      //
      //     // 更新配置
      //     controllers.config.mixedPort.value = newMixedPort;
      //     controllers.config.apiAddressPort.value = newApiPort;
      //     controllers.config.servicePort.value = newServicePort;
      //
      //     // 保存新的配置
      //     await controllers.config.saveConfig();
      //
      //     globalController.updateMsg("端口已更新,正在重新启动...");
      //   }
      // }


      // if(Platform.isMacOS){
      //   if (serviceController.serviceIsRuning) {
      //     await globalController.makeProxy();
      //     await serviceController.reloadClashCore();
      //     // await serviceController.fetchSetProxy();
      //   } else {
      //     // if (controllers.service.clashServiceIsRuning) {
      //     //   await globalController.makeProxy();
      //     //   await reloadClashCore();
      //     // }
      //   }
      // } else {
      //   // if (controllers.service.clashServiceIsRuning) {
      //   //   await globalController.makeProxy();
      //   //   await reloadClashCore();
      //   // }
      // }






      // if(Platform.isMacOS){
      //   if (serviceController.serviceIsRuning) {
      //     //await serviceController.fetchStartInit();
      //     await serviceController.fetchSetProxy();
      //     await globalController.openProxy();
      //   } else {
      //     if (controllers.service.clashServiceIsRuning) {
      //       globalController.connectStatus.value = true;
      //
      //     } else {
      //       throw Exception("内核启动失败");
      //     }
      //   }
      // } else {
      //   if (controllers.service.clashServiceIsRuning) {

      //
      //   } else {
      //     throw Exception("内核启动失败");
      //   }
      // }


      // updateStatus(ConnectionStatus.connected);
      // globalController.updateMsg("连接成功");
      // controllers.global.connectStatus.value = true;
      //
      // //检测系统代理并切换成网卡模式
      // if(Platform.isWindows){
      //
      //   if(!await proxyManager.isProxyEnabled()){
      //     globalController.updateMsg("当前没有设置系统代理,20秒后切换成网卡模式");
      //     await Future.delayed(Duration(seconds: 20)); // 等待核心状态更新
      //     // await globalController.TunProxySwitch(true);
      //     // await globalController.makeProxy();
      //     // await reloadClashCore();
      //     LogHelper().d("重置网卡模式");
      //   }
      //
      //
      // }


    } catch (e) {
      updateStatus(ConnectionStatus.disconnected);
      globalController.handleApiError("连接失败: $e");
    }
  }

  Future<void> stopConnection() async {
    try {
      updateStatus(ConnectionStatus.disconnected);
      globalController.updateMsg("正在断开连接...");

      if(Platform.isMacOS){
        if (serviceController.serviceIsRuning) {
          //await serviceController.stopClash();
          await serviceController.fetchSetProxyStop();

        } else {
          if (controllers.service.clashServiceIsRuning){
            //await controllers.service.stopClash();
            await globalController.closeProxy();
            globalController.updateMsg("内核已重新加载");
          } else {
            globalController.updateMsg("内核启动失败");
          }

        }
      } else{
        if (controllers.service.clashServiceIsRuning){
          //await controllers.service.stopClash();
          final proxyManager = WlBaseHelp();
          await proxyManager.stopProxy();
          // await globalController.closeProxy();
          globalController.updateMsg("内核已重新加载");
        } else {
          globalController.updateMsg("内核启动失败");
        }

      }


      globalController.connectStatus.value = false;
      updateStatus(ConnectionStatus.disconnected);
      globalController.updateMsg("已断开连接");
      controllers.global.connectStatus.value = false;
    } catch (e) {
      globalController.handleApiError("断开连接失败: $e");
    }
  }

  Future<void> reloadClashCore() async {
    try {
      globalController.updateMsg("正在重新加载内核...");

      if (serviceController.serviceIsRuning) {
        await serviceController.reloadClashCore();
        globalController.updateMsg("内核已重新加载");
        globalController.swift(globalController.selectedNode.value?.name ?? "");
        return;
      }
      if (controllers.service.clashServiceIsRuning){
        await controllers.service.reloadClashCore();
        globalController.updateMsg("内核已重新加载");
        globalController.swift(globalController.selectedNode.value?.name ?? "");
      } else {
        globalController.updateMsg("内核启动失败");
      }


    } catch (e) {
      globalController.handleApiError("重新加载内核失败: $e");
    }
  }

  Future<void> coreInit() async {
    try {


      globalController.updateMsg("正在初始化核心...");
      if (serviceController.installStatus.value) {
        //每次启动多要初始化
        await controllers.cc_service.fetchStartInit();
      } else {
        await controllers.service.initClashCoreConfig();
      }
      globalController.updateMsg("核心初始化完成");
    } catch (e) {
      globalController.updateMsg("失败...");
      globalController.handleApiError("核心初始化失败: $e");
    }
  }


  Future<void> installService() async{



    if(serviceController.serviceStatus.value == RunningState.stoped){
      controllers.service.stopClashCore();
      globalController.updateMsg("正在安装服务");
      await serviceController.serviceModeSwitch(true);


    }
  }



  Future<void> UninstallService() async{
    if(serviceController.serviceStatus.value == RunningState.running){
      controllers.global.updateMsg("正在卸载服务");
      await serviceController.serviceModeSwitch(false);

    }
  }



}