import 'package:flutter/material.dart';
import 'package:chewie/chewie.dart';
import 'package:video_player/video_player.dart';

class Html5Vid extends StatefulWidget {
  const Html5Vid({Key? key, required this.link, required this.title});
  final String link;
  final String title;
  @override
  State<Html5Vid> createState() => Html5VidState();
}

class Html5VidState extends State<Html5Vid> {
  late VideoPlayerController _videoPlayerController;
  late ChewieController _chewieController;
  bool _isVideoLoading = true;

  @override
  void initState() {
    super.initState();
    print(widget.link);
    print(widget.title);
    _videoPlayerController = VideoPlayerController.network('${widget.link}');
    _chewieController = ChewieController(
      videoPlayerController: _videoPlayerController,
      aspectRatio: 16 / 9,
      autoPlay: true,
      looping: false,
    );

    _videoPlayerController.addListener(() {
      if (_videoPlayerController.value.isInitialized &&
          !_videoPlayerController.value.isBuffering) {
        setState(() {
          _isVideoLoading = false;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        appBar: AppBar(
          title: Text('${widget.title}'),
        ),
        body: Stack(
          children: [
            Center(
              child: Chewie(
                controller: _chewieController,
              ),
            ),
            if (_isVideoLoading)
              Center(
                child: CircularProgressIndicator(),
              ),
          ],
        ),
      ),
    );
  }

  Future<bool> _onWillPop() async {
    await _videoPlayerController.pause();
    await _videoPlayerController.dispose();
    // await _chewieController.dispose();
    return true;
  }

  @override
  void dispose() {
    _videoPlayerController.dispose();
    _chewieController.dispose();
    super.dispose();
  }
}
