import 'dart:async';

import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/managers/interfaces/device.dart';
import 'package:flyinsono/views/common/device_live/device_live_detail/state.dart';
import 'package:flyinsono/views/desktop/hardware_detection/index.dart';
import 'package:flyinsono/views/desktop/hardware_detection/widgets/sonopost_live_panel.dart';
import 'package:get/get.dart';
import 'package:flyinsono/managers/interfaces/vboxcontrol.dart';
import 'package:fis_jsonrpc/services/device.m.dart';
import 'package:fis_ui/values/font_sizes.dart';
import 'package:fis_common/logger/logger.dart';

///Todo:finlay   测试魔盒
class SonopostDetaction extends StatefulWidget implements FPage {
  final bool isdetection;
  SonopostDetaction({Key? key, this.isdetection = false}) : super(key: key);

  @override
  String get pageName => "sonopost_detection";

  @override
  _SonopostDetactionState createState() => _SonopostDetactionState();
}

class _SonopostDetactionState extends State<SonopostDetaction> {
  bool vBoxLogin = false;
  final _deviceManager = Get.find<IDeviceManager>();
  final _vboxControlManager = Get.find<IVBoxControlManager>();
  final _hardWareController = Get.find<HardwareDetectionController>();
  DeviceStateModel? model;
  DeviceExtendInfoDTO? deviceInfo;
  late TextStyle smallTitleStyle = TextStyle(
    fontSize: widget.isdetection ? FFontSizes.H4 : FFontSizes.H6,
    height: 1,
  );
  @override
  void initState() {
    super.initState();

    Timer timer;
    int count = 0;
    vBoxLogin = false;
    timer = Timer.periodic(Duration(milliseconds: 2000), (timer) async {
      if (vBoxLogin) {
        logger.w("Since snonopost login, sonopost check stopped");
        timer.cancel();
        vBoxLogin = false;
        return;
      }
      count++;
      _loadSonopost();
      logger.i("Load sonopost time: $count");
      if (count == 10) {
        logger.w(
            "Since snonopost not login for 10 seconds, sonopost check stopped");
        timer.cancel();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _deviceManager.exitLiveRoom(deviceInfo?.deviceCode ?? '');
  }

  void _loadSonopost() async {
    try {
      if (_hardWareController.state.searchingCamera) {
        logger.w("FIS searching camera stop sonopost live test");
        return;
      }
      if (widget.isdetection) {
        try {
          _hardWareController.stopDetectingCamera();
        } catch (e) {
          logger.w("Stop camera detecting while load sonopost live");
        }
      }
      var shortCode = await _vboxControlManager.getUltrasoundUniqueId();
      if (shortCode == "") {
        logger.w("Sonopost not started yet,or sonopost not login.");
        return;
      }
      deviceInfo = await _deviceManager.getDeviceByShortCode(shortCode);
      vBoxLogin = true;
      var uniqueCode = deviceInfo?.deviceCode ?? '';
      if (uniqueCode == null || uniqueCode == '') {
        logger.w("Snonopost not login waiting again");
      }

      _hardWareController.state.deviceCode = deviceInfo?.deviceCode ?? '';
      if (_hardWareController.state.detectingCamera) {
        logger.w("Cameara detecting do not watch sonopost live");
        return;
      }
      var liveInfo =
          await _deviceManager.enterLiveRoom(deviceInfo?.deviceCode ?? '');

      setState(() {
        model = DeviceStateModel(deviceInfo!, liveInfo: liveInfo);
      });
    } catch (e) {
      logger.e("Load sonopost error", e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.centerLeft,
      width: 1024,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          if (!widget.isdetection)
            Container(
              alignment: Alignment.centerLeft,
              child: Text(
                i18nBook.setting.sonopostDetetion.t,
                style: smallTitleStyle,
              ),
            ),
          if (widget.isdetection)
            Center(
              child: Text(
                i18nBook.setting.sonopostDetetion.t,
                style: smallTitleStyle,
              ),
            ),
          SizedBox(height: 5),
          Container(
            alignment: Alignment.centerLeft,
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey[300]!),
              borderRadius: BorderRadius.circular(5),
              color: Colors.grey[200]!,
            ),
            height: 576,
            child: model == null ? Container() : SonopostLivePanel(model!),
          ),
        ],
      ),
    );
  }
}
