import 'dart:convert';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_superplayer/flutter_superplayer.dart';

const _kControlViewTypes = [kControlViewTypeDefault, kControlViewTypeWithout];

class SuperPlayerPage extends StatefulWidget {
  SuperPlayerPage({@required this.url, this.loop = 1, this.title = 'Tencent Player', Key key})
      : super(key: key);
  String url;
  String title;
  int loop; //设置播放循环，默认播放器的循环次数是1， 即不循环播放。如果设置循环次数0，表示无限循环。

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

class _SuperPlayerPageState extends State<SuperPlayerPage> with SuperPlayerListener {
  SuperPlayerController _playerController = SuperPlayerController();

  String _sdkVersion = 'Unknown';
  List<String> _logs = [];
  bool bFullScreen = false;

  String _controlViewType = _kControlViewTypes.first;

  @override
  void initState() {
    super.initState();
    //initPlatformState();
    // Future.delayed(const Duration(milliseconds: 1000), () {
    //   _playerController.playWithModel(SuperPlayerModel(url: widget.url));
    //   setState(() {
    //   });
    // });
    init();
  }

  Future<void> init() async {
    await _playerController.addListener(this);
    await initPlatformState();
    if (!mounted) return;
    print('mounted = ${mounted}');
    // 开启调试日志
    //await FTXPlayerController.setConsoleEnabled(true);
    // 初始化播放器
    //await _controller.initialize(onlyAudio: true);
    await _playerController.uiHideDanmu();
    //设置播放循环，默认播放器的循环次数是1， 即不循环播放。如果设置循环次数0，表示无限循环。
    if (0 == widget.loop) {
      await _playerController.setLoop(true);
    }
    await _playerController.playWithModel(testSuperPlayerModel);
    //_controller.play("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
    // _controller
    //     .play('rtmp://125.64.218.67:9901/rtp/gb_play_34020000001320003016_34020000001320003016');
    // 设置循环播放
    //await _controller.setLoop(true);
    // 开始播放
    //await _controller.play("http://125.64.218.67:9908/video/2_6063_20210409_140608_川Q31715.mp4");
  }

  SuperPlayerModel get testSuperPlayerModel {
    // int appId = 1252463788;
    // String fileId = "5285890781763144364";

    SuperPlayerModel superPlayerModel = SuperPlayerModel(
      url: widget.url,
      // appId: appId,
      // videoId: SuperPlayerVideoId(fileId: fileId),
    );
    return superPlayerModel;
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String sdkVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      sdkVersion = await FlutterSuperPlayer.sdkVersion;
    } on PlatformException {
      sdkVersion = 'Failed to get platform version.';
    }
    print('sdkVersion = ${sdkVersion}');
    print('mounted = ${mounted}');

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _sdkVersion = sdkVersion;
    });
  }

  void _addLog(String method, dynamic data) {
    _logs.add('>>>$method');
    if (data != null) {
      _logs.add(data is Map ? json.encode(data) : data);
    }
    _logs.add(' ');

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Align(
        alignment: Alignment(0, 0),
        child: Container(
          padding:
              EdgeInsets.only(top: bFullScreen ? 0 : MediaQueryData.fromWindow(window).padding.top),
          alignment: Alignment(0, 0),
          width: MediaQuery.of(context).size.width,
          child: SuperPlayerView(
            controller: _playerController,
            controlViewType: _controlViewType,
          ),
        ),
      ),
    );
  }

  @override
  void onClickFloatCloseBtn() {
    _addLog('onClickFloatCloseBtn', {});
  }

  @override
  void onClickSmallReturnBtn() {
    _addLog('onClickSmallReturnBtn', {});
    Navigator.maybePop(context);
  }

  @override
  void onFullScreenChange(bool isFullScreen) {
    _addLog('onFullScreenChange', {'isFullScreen': isFullScreen});
    bFullScreen = !bFullScreen;
    setState(() {});
  }

  @override
  void onPlayProgressChange(int current, int duration) {
    _addLog('onPlayProgressChange', {'current': current, 'duration': duration});
  }

  @override
  void onPlayStateChange(int playState) {
    _addLog('onPlayStateChange', {'playState': playState});
  }

  @override
  void onStartFloatWindowPlay() {
    _addLog('onStartFloatWindowPlay', {});
  }
}
