import 'dart:collection';
import 'dart:typed_data';
import 'package:fis_measure/view/frame_view/native/frame_view.dart';
import 'package:fis_measure/view/player/controller.dart';
import 'package:fis_measure/view/player/enums.dart';
import 'package:fis_measure/view/player/events.dart';
import 'package:flutter/material.dart';

///基于图片组件的播放器
class VidImagePlayer extends StatefulWidget {
  const VidImagePlayer(
    this.controller, {
    Key? key,
    this.width,
    this.height,
  }) : super(key: key);

  final VidPlayerController controller;

  final double? width;
  final double? height;

  @override
  State<StatefulWidget> createState() => _VidImagePlayerState();
}

class _VidImagePlayerState extends State<VidImagePlayer> {
  Uint8List? frameBytes;
  DateTime lastFrameTime = DateTime.now();
  ListQueue<int> frames = ListQueue<int>()..addFirst(30); //预留一位防止分母为0
  int maxFramesNum = 10;
  int curFPS = 30;

  @override
  void initState() {
    widget.controller.eventHandler.addListener(onControllerEvent);
    super.initState();
  }

  @override
  void didUpdateWidget(covariant VidImagePlayer oldWidget) {
    if (oldWidget.controller != widget.controller) {
      throw UnsupportedError("[VidTestPlayer] unsupport replace controller.");
    }
    super.didUpdateWidget(oldWidget);
  }

  void onControllerEvent(Object sender, VidPlayerEvent e) {
    if (e is VidPlayerStatusChangeEvent) {
      if (!widget.controller.hasView) {
        setState(() {});
      }
    }
    if (e is VidPlayerFrameIndexChangeEvent) {
      onFrameChanged(e);
    }
    if (e is VidPlayerBrightnessChangeEvent) {
      updateFrame();
    }
    if (e is VidPlayerContrastChangeEvent) {
      updateFrame();
    }
  }

  void onFrameChanged(VidPlayerFrameIndexChangeEvent e) {
    countCurFPS(); //计算视频帧率
    setState(() {
      frameBytes = e.bytes;
    });
  }

  void updateFrame() {
    setState(() {});
  }

  void countCurFPS() {
    int fps = 1000 ~/ DateTime.now().difference(lastFrameTime).inMilliseconds;
    lastFrameTime = DateTime.now();
    frames.addFirst(fps);
    while (frames.length > maxFramesNum) {
      frames.removeLast();
    }
    curFPS = frames.reduce((a, b) => a + b) ~/ frames.length;
  }

  @override
  Widget build(BuildContext context) {
    Widget? child;
    switch (widget.controller.status) {
      case VidPlayStatus.init:
        child = const Text("Loading");
        break;
      case VidPlayStatus.ready:
        child = const Text("Ready");
        break;
      case VidPlayStatus.loadFail:
        child = const Text("Load fail");
        break;
      case VidPlayStatus.play:
      case VidPlayStatus.pause:
        child = buildFrameView(context);
        break;
      case VidPlayStatus.stop:
      case VidPlayStatus.dispose:
        child = const Text("Closed");
        break;
    }
    return buildBox(context, child);
  }

  ///创建播放器容器，可以在此叠加信息
  Widget buildBox(BuildContext context, Widget child) {
    return Stack(
      children: [
        Text("当前帧：${widget.controller.currentFrameIndex}\n 估算平均帧率：$curFPS fps"),
        Container(
          alignment: Alignment.center,
          child: child,
        ),
      ],
    );
  }

  Widget buildFrameView(BuildContext context) {
    if (frameBytes != null) {
      final size = MediaQuery.of(context).size;
      return VidFrameView(
        frameBytes!,
        width: size.width,
        height: size.height,
      );
    } else {
      return Container();
    }
  }

  @override
  void dispose() {
    widget.controller.eventHandler.removeListener(onControllerEvent);
    super.dispose();
  }
}
