import 'package:flutter/foundation.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/managers/interfaces/network_error_handler.dart';
import 'package:flyinsono/managers/interfaces/server_config.dart';
import 'package:flyinsono/managers/interfaces/webview_controller.dart';
import 'package:flyinsono/pages/upgrade/upgrade_wrapper.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:flyinsono/managers/interfaces/vboxcontrol.dart';
import 'package:fis_common/logger/logger.dart';
import 'index.dart';

///主页页面控制器
class HomePageController extends FControllerBase {
  HomePageController();

  final state = HomePageState();
  INetworkErrorHandlerManager networkErrorHandlerManager =
      Get.find<INetworkErrorHandlerManager>();

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

  @override
  void onInit() {
    super.onInit();
    networkErrorHandlerManager.onNetworkInterruption
        .addListener(_onNetworkInterruption);
    if (CartSystemPlatform.isCartSystemVersion) {
      logger.i("Start binding data");
      _bingSonopostUnique();

      gotoHardwareDetector();
    }
  }

  void gotoHardwareDetector() async {
    if (Get.context != null) {
      await UpgradeWrapper.invokeUpgradeDirectly(Get.context!, false);
    }
    await Future.delayed(Duration(milliseconds: 1000), () {
      var vBoxManager = Get.find<IVBoxControlManager>();
      if (vBoxManager.canShowHardwareDetector) {
        var uri = Uri.parse(rpc.currentHostAddress);
        CartSystemPlatform.synchServerAddressToSonopost(
            uri.host, uri.port.toString());

        router.offAll(RouteNames.User.DetectionAssistant);
      }
      vBoxManager.canShowHardwareDetector = false;
    });
  }

  @override
  void dispose() {
    Get.find<IWebviewControllerManager>().disposeWebviewController();
    networkErrorHandlerManager.onNetworkInterruption
        .removeListener(_onNetworkInterruption);
    super.dispose();
  }

  void _onNetworkInterruption(sender, e) {
    state.showNetworkError = e;
  }

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

  ///跟据Token获取主页显示的地址
  Future<String?> _getPersonHomePageUrl() async {
    var serverConfigManager = Get.find<IServerConfigManager>();
    var cmsUrl = await serverConfigManager.getCMSUrl();
    if (cmsUrl != null) {
      state.cmsUrl = cmsUrl;
      return cmsUrl;
    }
    return null;
  }

  Future _bingSonopostUnique() async {
    var vBoxManager = Get.find<IVBoxControlManager>();
    await vBoxManager.bindSonopostUniqueCode();
  }
}
