
import 'dart:io';

import 'package:dart_json_mapper/dart_json_mapper.dart';
import 'package:get/get.dart';
import 'package:tray_manager/tray_manager.dart';
import 'package:window_manager/window_manager.dart';
import '../../../common/LogHelper.dart';
import '../../../common/SharedPreferencesUtil.dart';
import '../../../data/model/LocalUser.dart';
import '../../../data/model/NodeMode.dart';
import '../../../data/model/SysConfig.dart';
import '../../../data/model/UserMode.dart';
import '../../../global_controller/GlobalController.dart';
import '../../../network/api_service.dart';
import '../../../routes/app_pages.dart';
import '../../../service/clash_service.dart';

enum ImageType {
  CUSTOMER,
  PROMOTION,
  TUTORIAL,
  RENEWAL,
}

class HomeController extends GetxController with TrayListener,WindowListener {
  //TODO: Implement HomeController

  var isLoading = false.obs;
  var sysConfig = SysConfig().obs;
  var localUsers = LocalUser().obs;
  var userMode = User().obs;
  var errorMsg = ''.obs;
  var selectNode = '选择节点'.obs;
  var nodeModes = <NodeMode>[];
  late final GlobalController globalController ;


  final Map<ImageType, String> imageMap = {
    ImageType.CUSTOMER: "assets/images/main/customer.png",
    ImageType.PROMOTION: "assets/images/main/promotion.png",
    ImageType.TUTORIAL: "assets/images/main/tutorial.png",
    ImageType.RENEWAL: "assets/images/main/renewal.png",
  };

  void onImageTap(ImageType type) {
    if(type == ImageType.CUSTOMER){

    } else if (type == ImageType.PROMOTION){

    } else if (type == ImageType.TUTORIAL){

    } else if (type == ImageType.RENEWAL){

    }
    LogHelper().d("${imageMap[type]} tapped as ${type.toString().split('.').last}");
  }

  Future<void> fetchSysConfig() async {
    try {
      String? data  = await SharedPreferencesUtil().getString("sysconfig");
      if(data  != null){
        sysConfig.value =JsonMapper.deserialize<SysConfig>(data)!;
      }

    } catch (e) {
      errorMsg.value = e.toString();
    } finally {
    }
  }
  
  Future<void> fetchUserinfo() async {
    try {
      isLoading.value = true;
      userMode.value = await ApiService().userinfo("/api/client/v4/userinfo");
      await globalController.fetchNodes();
    } catch (e) {
      errorMsg.value = e.toString();
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> fetchNode() async {
    try {
      isLoading.value = true;
      await globalController.fetchNodes();
    } catch (e) {
      errorMsg.value = e.toString();
    } finally {
      isLoading.value = false;
    }
  }

  //await SharedPreferencesUtil().setObject("localUser", userModes.toJson());

  Future<void> fetchLocalUser() async {
    try {
      String? userdata  = await SharedPreferencesUtil().getString("localUser");
      if(userdata  != null){
        localUsers.value = JsonMapper.deserialize<LocalUser>(userdata)!;
      }
    } catch (e) {
      errorMsg.value = e.toString();
    } finally {
    }
  }


  final count = 0.obs;
  @override
  void onInit() {
    super.onInit();
    globalController = Get.put(GlobalController());
    fetchSysConfig();
    fetchLocalUser();
    fetchUserinfo();
    windowManager.addListener(this);
    trayManager.addListener(this);
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }


  @override
  void onWindowClose() {
    super.onWindowClose();
    windowManager.hide();
  }

  @override
  void onTrayIconMouseDown() {
    // windowManager.focus();
    windowManager.show();
  }

  @override
  void onTrayIconRightMouseDown() {
    super.onTrayIconRightMouseDown();
    trayManager.popUpContextMenu();
  }

  @override
  void onTrayMenuItemClick(MenuItem menuItem) {
    switch (menuItem.key) {
      case 'exit':
        windowManager.close().then((value) async {
          await Get.find<ClashService>().closeClashDaemon();
          exit(0);
        });
        break;
      case 'show':
        windowManager.focus();
        windowManager.show();
    }
  }


  bool   GetEnable()  => userMode.value.enable == 1;
  String GetUserName() => localUsers.value.email.toString();
  String GetExpiredAt() => "到期时间:${userMode.value.expiredAt}";
  String GetTraffic() => "用户流量:${userMode.value.unusedTraffic}";
  String GetNode() => selectNode.value;


  void RouteNode() =>  Get.toNamed(Routes.NODE);
}
