import 'dart:convert';

import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/global.dart';
import 'package:webviewx/webviewx.dart';
import 'package:fis_ui/widgets/webview/webview.dart';
import 'package:flutter/material.dart';
import 'package:fis_ui/index.dart';

/// 来自外部资源的直播播放器（资源域名需包含 fis.plus）
class DeviceLiveWebViewFromFisPlus extends FStatelessWidget {
  final String sourceUrl; // 资源地址
  final String deviceCode; // 设备编码

  DeviceLiveWebViewFromFisPlus({
    this.sourceUrl = "http://ru.fis.plus:8080/open/device_live.html",
    required this.deviceCode,
  });

  @override
  FWidget build(BuildContext context) {
    final String sourceURL =
        "$sourceUrl?code=inApp&token=${Store.user.token}&deviceCode=$deviceCode&serverHostBase64=${_getServerHostBase64()}";
    return FLayoutBuilder(
      builder: (context, constraints) {
        final webview = FWebViewX(
          height: constraints.maxHeight,
          width: constraints.maxWidth,
          initialContent: sourceURL,
          initialSourceType: SourceType.url,
          javascriptMode: JavascriptMode.unrestricted,
          ignoreAllGestures: false,
          onWebViewCreated: (controller) {
            // webViewController = controller;
            // webviewControllerManager.initWebviewController(controller);
          },
          onPageFinished: (p0) {
            // webviewControllerManager.disposeWebviewController();
            // webViewController.callJsMethod('load', [json]);
          },
        );
        return webview;
      },
    );
  }

  /// aHR0cDovLzE5Mi4xNjguNi42OjgzMDMv
  /// http://192.168.6.6:8303/
  String _getServerHostBase64() {
    String serverHost = Global.config.data.server.current ?? '';
    if (!serverHost.endsWith('/')) {
      serverHost = serverHost + '/';
    }
    return btoa(serverHost);
  }

  String btoa(String input) {
    return base64.encode(utf8.encode(input));
  }
}
