import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:vitalapp/consts/devices.dart';
import 'package:vitalapp/database/db.dart';
import 'package:vnote_device_plugin/consts/status.dart';
import 'package:vnote_device_plugin/events/global_event_handler.dart';
import 'package:vnote_device_plugin/vnote_device_plugin_platform_interface.dart';
import 'package:vitalapp/architecture/network_connectivity.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/managers/index.dart';
import 'package:vitalapp/managers/interfaces/permission.dart';
import 'package:vitalapp/rpc.dart';
import 'package:vitalapp/store/store.dart';
import 'package:fis_common/logger/logger.dart';

import 'architecture/app_parameters.dart';

/// 【全局】 是否在线
bool get kIsOnline => netChecker.isOnline;

abstract class Global {
  static Future<void> init() async {
    logger.i("Global init start...");

    // 锁定横屏
    await SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);

    // SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);

    SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersive);
    SystemChrome.setSystemUIChangeCallback((systemOverlaysAreVisible) async {
      await Future.delayed(const Duration(seconds: 1));
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersive);
    });
    SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.light,
      ),
    );
    // SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);

    // 日志
    if (kReleaseMode) {
      // 生产环境
      Get.isLogEnable = false;
    } else {
      // debug/profile 环境
      logger.setMinimumLevel(LogLevel.Degbug);
    }
    await logger.init();

    // Loading工具
    PromptBox.init();

    /// 预设配置
    await AppParameters.load();

    // 状态
    await Store.init();

    // 开始检测网络状态
    netChecker.run();

    await db.init();

    _initRpc();

    /// 全局管理器中心
    ManagerCenter.load();

    /// 初始化动态权限
    _initPermission();

    /// 设备测量插件初始化
    await _initDevices();

    logger.i("Global init finish...");
  }

  static void _initRpc() {
    RpcSettingCache.setRpcHostPath(Store.app.serverUrl);
  }

  static Future<void> _initPermission() async {
    IPermissionManager permissionManager = Get.find<IPermissionManager>();

    await permissionManager.requestLocationPermission();
    await permissionManager.requestBluetoothConnectPermission();
    await permissionManager.requestBluetoothAdvertisePermission();
    await permissionManager.requestBluetoothScanPermission();
    await permissionManager.requestInstallPackagesPermission();
  }

  static Future<void> _initDevices() async {
    await VnoteDevicePluginPlatform.instance.init();

    final List<_DeviceStatusTipsHandler> statusHandlers = [];
    for (int status in DeviceConsts.STATUS_DESC_MAP.keys) {
      final message = DeviceConsts.STATUS_DESC_MAP[status]!;
      statusHandlers.add(_DeviceStatusTipsHandler(status, message));
    }

    GlobalDeviceEventHandler.setup(statusHandlers: statusHandlers);
  }
}

class _DeviceStatusTipsHandler extends DeviceEventStatusHandler {
  late final String _msg;
  _DeviceStatusTipsHandler(int status, String msg) : super(status) {
    _msg = msg;
  }

  String get message => _msg;

  @override
  void handle(Map<String, dynamic>? data) {
    // PromptBox.toast(message);
    Get.snackbar("提示", message);
  }
}
