import 'dart:async';
import 'dart:io';

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

class VideoWidget extends StatefulWidget {
  final bool play;
  final bool isServerFile;
  final String pathFile;

  const VideoWidget({Key? key, required this.pathFile, required this.play, required this.isServerFile}) : super(key: key);

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

class _VideoWidgetState extends State<VideoWidget> {
  VideoPlayerController? videoPlayerController;
  late Future<void> _initializeVideoPlayerFuture;

  @override
  void initState() {
    super.initState();
    if (widget.isServerFile) {
      videoPlayerController = VideoPlayerController.network(widget.pathFile);
    } else {
      videoPlayerController = VideoPlayerController.file(File(widget.pathFile));
    }

    _initializeVideoPlayerFuture = videoPlayerController!.initialize().then((_) {
      //       Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
      videoPlayerController?.play();
      videoPlayerController?.setVolume(0.0);
      Timer.periodic(const Duration(seconds: 1), (_) {
        videoPlayerController?.pause();
      });
      setState(() {});
    });
  }

  @override
  void dispose() {
    videoPlayerController?.dispose();
    print("dispose video item");
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _initializeVideoPlayerFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return Container(
            child: Container(
              key: PageStorageKey(widget.pathFile),
              child: Container(
                padding: const EdgeInsets.all(1),
                width: 100,
                height: 100,
                decoration: BoxDecoration(
                    color: Colors.white, border: Border.all(color: Colors.red), borderRadius: const BorderRadius.all(Radius.circular(8.0))),
                child: VideoPlayer(videoPlayerController!),
              ),
            ),
          );
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }
}
