/// @author ilex.h

import 'package:flutter/material.dart';
import 'package:fijkplayer/fijkplayer.dart';
import 'package:jcs_airport/view/workBench/realTimeMonitoring/monitorVideo/video_panel.dart';

/// 流媒体播放器
///
/// [fijkplayer doc](https://fijkplayer.befovy.com/docs/zh/hello-world.html)
///
/// 底层采用 [ijkplayer](https://github.com/bilibili/ijkplayer/)
///
class StreamMediaPlayer extends StatefulWidget {
  const StreamMediaPlayer({Key key, @required this.url, this.toggleAppbar}) : super(key: key);

  /// 视频直播 url，支持 hls 和 rtsp， 其它模式也支持
  final String url;
  final Function toggleAppbar;

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

class _StreamMediaPlayerState extends State<StreamMediaPlayer> {
  final FijkPlayer _player = FijkPlayer();

  @override
  void initState() {
    super.initState();
    _initPlayer();
  }

  Future<void> _initPlayer() async {
    /// ijkPlayer 初始化不启用缓冲，避免 RTSP 流卡死
    await _player.setOption(FijkOption.playerCategory, 'packet-buffering', 0);
    await _player.setOption(FijkOption.playerCategory, 'framedrop', 1);
    _player.setDataSource(widget.url, autoPlay: true).catchError((e) {
      print('setDataSource error: $e');
    });
  }

  /// 切换播放源
  Future<void> _changePlayer() async {
    await _player.stop();
    await _player.reset();
    _player.setDataSource(widget.url, autoPlay: true).catchError((e) {
      print('setDataSource error: $e');
    });
  }

  @override
  void didUpdateWidget(covariant StreamMediaPlayer oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.url != widget.url) {
      _changePlayer();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: FijkView(
        player: _player,
        fit: FijkFit.fill,
        panelBuilder: (FijkPlayer player, FijkData data, BuildContext context, Size viewSize, Rect texturePos) {
          return CustomFijkPanel(
            player: player,
            buildContext: context,
            viewSize: viewSize,
            texturePos: texturePos,
            toggleAppbar: widget.toggleAppbar,
          );
        },
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _player.release();
  }
}
