import 'dart:async';
import 'dart:convert';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/rpc.dart';
import 'package:flyinsono/managers/base_manager.dart';
import 'package:fis_common/logger/logger.dart';
import 'interfaces/vboxcontrol.dart';
import 'package:fis_jsonrpc/rpc.dart';

//class DeviceManager extends BaseManager implements IDeviceManager {
class VBoxControlManager extends BaseManager implements IVBoxControlManager {
  bool vBoxLogin = false;
  bool vBoxCheckStarted = false;
  bool _canShowHardwareDetector = true;

  @override
  bool get canShowHardwareDetector => _canShowHardwareDetector;

  @override
  set canShowHardwareDetector(bool newValue) {
    _canShowHardwareDetector = newValue;
  }

  ///获取当前设备唯一码
  @override
  Future<String> getUltrasoundUniqueId() async {
    return await rpc.platform.getUltrasoundUniqueId();
  }

  ///获取网卡信息
  @override
  Future<NetworkResult> getNetworkCardsInfo() async {
    var jsonInfo = await rpc.platform.getNetworkCardsInfo();
    //'{"IsSuccess":true,"Data":{"Interfaces":[{"Guid":"4b145aab-608a-4532-b482-9cead86a820c","MacAddress":"C0-FB-F9-CE-DA-14","Name":"EthernetInterface1","Description":"Realtek PCIe GBE Family Controller #5","EnableDHCP":false,"IPAddress":"192.168.6.106","SubnetMask":"255.255.255.0","Gateway":"192.168.6.1","PreferredDNS":"61.177.7.1","StandbyDNS":"221.228.255.1"},{"Guid":"448f7b48-ebfd-4606-b179-d01a3c8dece9","MacAddress":"C0-FB-F9-CE-DA-15","Name":"EthernetInterface2","Description":"Realtek PCIe GBE Family Controller #4","EnableDHCP":true,"IPAddress":"","SubnetMask":"","Gateway":"","PreferredDNS":"","StandbyDNS":""}]}}';
    var result = NetworkResult.fromJson(jsonDecode(jsonInfo));
    return result;
  }

  ///保存网卡信息
  @override
  Future<bool> saveNetworkCardsInfo(String networkWireListModel) async {
    return await rpc.platform.saveNetworkCardsInfo(networkWireListModel);
  }

  ///获取wifi网络
  @override
  Future<NetworkWifiResult> getWirelessCardInfo() async {
    var jsonInfo = await rpc.platform.getWirelessCardInfo();
    //'{"IsSuccess":true,"Data":{"Points":[{"Name":"IDS-WIFI-5G","SignalStrength":"100","HasProfile":false,"IsSecure":true,"IsConnected":false},{"Name":"SXQN-5604","SignalStrength":"84","HasProfile":false,"IsSecure":true,"IsConnected":false},{"Name":"vinno","SignalStrength":"84","HasProfile":false,"IsSecure":true,"IsConnected":false},{"Name":"IDS-WIFI","SignalStrength":"70","HasProfile":false,"IsSecure":true,"IsConnected":false},{"Name":"TP-LINK_F384","SignalStrength":"64","HasProfile":false,"IsSecure":true,"IsConnected":false},{"Name":"ChinaNet-G2H9","SignalStrength":"64","HasProfile":false,"IsSecure":true,"IsConnected":false},{"Name":"ChinaNet-G2H9-Guest","SignalStrength":"64","HasProfile":false,"IsSecure":true,"IsConnected":false},{"Name":"yihulukeji","SignalStrength":"63","HasProfile":false,"IsSecure":true,"IsConnected":false},{"Name":"IRON","SignalStrength":"62","HasProfile":false,"IsSecure":true,"IsConnected":false},{"Name":"ChinaNet-G2H9-5G","SignalStrength":"61","HasProfile":false,"IsSecure":true,"IsConnected":false},{"Name":"ChinaNet-DQtR","SignalStrength":"58","HasProfile":false,"IsSecure":true,"IsConnected":false},{"Name":"ChinaNet-5584","SignalStrength":"48","HasProfile":false,"IsSecure":true,"IsConnected":false},{"Name":"HUAWEI-HZL6MW","SignalStrength":"47","HasProfile":false,"IsSecure":true,"IsConnected":false},{"Name":"vinno-SZ","SignalStrength":"42","HasProfile":false,"IsSecure":true,"IsConnected":false},{"Name":"TT0106f000030AQ0332GT003","SignalStrength":"28","HasProfile":false,"IsSecure":false,"IsConnected":false}],"Guid":"2e546f25-4f19-4752-91fc-7ac0101102f4","MacAddress":"08-1F-71-58-13-4E","Name":"TP-Link Wireless USB Adapter","Description":"TP-Link Wireless USB Adapter","EnableDHCP":true,"IPAddress":"","SubnetMask":"","Gateway":"","PreferredDNS":"","StandbyDNS":""}}';
    if (jsonInfo.isEmpty) {
      return new NetworkWifiResult(isSuccess: false);
    } else {
      Map<String, dynamic> responseJson = jsonDecode(jsonInfo);
      NetworkWifiResult networkWifiResult =
          NetworkWifiResult.fromJson(responseJson);
      return networkWifiResult;
    }
  }

  ///保存Wifi网络信息
  @override
  Future<bool> saveWifiNetworkCard(String networkInterface) async {
    return await rpc.platform.saveWifiNetworkCard(networkInterface);
  }

  ///连接wifi网络
  @override
  Future<bool> connectWifi(NetworkConnectWifi wifiInfo) async {
    var jsonInfo = jsonEncode(wifiInfo.toJson());
    return await rpc.platform.connectWifi(jsonInfo);
  }

  ///断开wifi网络
  @override
  Future<bool> disconnectWifi(NetworkConnectWifi wifiInfo) async {
    var jsonInfo = jsonEncode(wifiInfo.toJson());
    return await rpc.platform.disconnectWifi(jsonInfo);
  }

  ///忘记wifi密码
  @override
  Future<bool> forgetWifiPassword(NetworkConnectWifi wifiInfo) async {
    var jsonInfo = jsonEncode(wifiInfo.toJson());
    return await rpc.platform.forgetWifiPassword(jsonInfo);
  }

  ///刷新DNS
  @override
  Future<bool> flushDNS() async {
    return await rpc.platform.flushDNS();
  }

  ///Ping 测试Ip是否可以连接
  @override
  Future<bool> ping(String ipInfo) async {
    return await rpc.platform.ping(ipInfo);
  }

  @override
  Future<void> bindSonopostUniqueCode() async {
    if (vBoxCheckStarted) {
      return;
    }
    vBoxCheckStarted = true;
    await _bindSonopostUniqueId();
  }

  _bindSonopostUniqueId() async {
    try {
      Timer timer;
      int count = 0;

      timer = Timer.periodic(Duration(milliseconds: 2000), (timer) async {
        count++;
        await _loadSonopost();
        logger.i("Load sonopost time: $count");
        if (vBoxLogin) {
          timer.cancel();
          logger.i(
              "Load sonopost cancelled since load success, load count is : $count");
        }
      });
    } catch (e) {
      logger.e("Error happened while trying binding sonopost unique id", e);
    }
  }

  _loadSonopost() async {
    try {
      var shortCode = await getUltrasoundUniqueId();

      if (shortCode == null || shortCode == '') {
        logger.w("Snonopost not login waiting again");
        return;
      }

      PageCollection<DeviceExtendInfoDTO> result;
      GetPersonDeviceRequest request = GetPersonDeviceRequest(
        token: Store.user.token,
        pageIndex: 1,
        pageSize: 20,
        keyWord: shortCode,
        organizationCodes: [],
      );

      result = await rpc.device.getPersonDeviceListAsync(request);
      bool hasShortCode = result.pageData!
          .toList()
          .any((element) => element.shortCode == shortCode);
      if (hasShortCode) {
        logger.w("$shortCode already added to user device list");
        vBoxLogin = true;
        return;
      }
      var bindDeviceResult =
          await rpc.device.scanBindDeviceAsync(ScanBindDeviceRequest(
        token: Store.user.token,
        shortCode: shortCode,
      ));
      if (bindDeviceResult) {
        logger.i("Binding unique code success, code is: $shortCode");
      } else {
        logger.e("Binding unique code failed, code is: $shortCode");
      }
      vBoxLogin = true;
    } catch (e) {
      logger.e("Load sonopost error", e);
    }
  }
}
