import 'dart:async';
import 'dart:io';
import 'package:get/get.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 '../controller/GlobalController.dart';
import '../modules/home/controllers/home_controller.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> startConnection() async {
    try {

      // // 检查所有内核是否已停止
      // 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("端口已更新,正在重新启动...");
      //   }
      // }
      updateStatus(ConnectionStatus.connecting);
      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();
        }
      }

      await globalController.updateNode();


      // 等待连接建立
      await Future.delayed(Duration(seconds: 2));

      if(Platform.isMacOS){
        if (serviceController.serviceIsRuning) {
          //await serviceController.fetchStartInit();
          await serviceController.fetchSetProxy();

        } else {
          if (controllers.service.clashServiceIsRuning) {
            globalController.connectStatus.value = true;
            await globalController.openProxy();
          } else {
            throw Exception("内核启动失败");
          }
        }
      } else {
        if (controllers.service.clashServiceIsRuning) {
          updateStatus(ConnectionStatus.connected);
          globalController.connectStatus.value = true;
          globalController.updateMsg("连接成功");

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

      updateStatus(ConnectionStatus.connected);
      globalController.updateMsg("连接成功");
      controllers.global.connectStatus.value = true;

    } 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();
          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);

    }
  }



}