import 'package:flutter/material.dart';
import 'dart:math' as math;
import '../controller/video_player_controller.dart';
import '../platform/nut_player_platform.dart';

class VideoPlayer extends StatefulWidget {

  final VideoPlayerController controller;

  const VideoPlayer(this.controller, {super.key});

  @override
  State<VideoPlayer> createState() => _VideoPlayerState();
}

typedef PlayerId = int;

class _VideoPlayerState extends State<VideoPlayer> {

  late VoidCallback _listener;
  late PlayerId? _playerId;

  _VideoPlayerState() {
    _listener = () {
      final PlayerId? newPlayerId = widget.controller.playerId;
      if (newPlayerId != _playerId) {
        setState(() {
          _playerId = newPlayerId;
        });
      }
    };
  }

  @override
  void initState() {
    super.initState();
    _playerId = widget.controller.playerId;
    widget.controller.addListener(_listener);
  }

  @override
  void deactivate() {
    super.deactivate();
    widget.controller.removeListener(_listener);
  }

  @override
  void didUpdateWidget(VideoPlayer oldWidget) {
    super.didUpdateWidget(oldWidget);
    oldWidget.controller.removeListener(_listener);
    _playerId = widget.controller.playerId;
    widget.controller.addListener(_listener);
  }

  @override
  Widget build(BuildContext context) {
    final playerId = _playerId;
    return playerId == null
        ? Container()
        : _VideoPlayerWithRotation(
      rotation: widget.controller.value.rotationCorrection,
      child: nutPlayerPlatform.buildView(playerId),
    );
  }
}

class _VideoPlayerWithRotation extends StatelessWidget {
  const _VideoPlayerWithRotation({required this.rotation, required this.child});

  final int rotation;
  final Widget child;

  @override
  Widget build(BuildContext context) => rotation == 0
      ? child
      : Transform.rotate(
    angle: rotation * math.pi / 180,
    child: child,
  );
}