import 'dart:convert';
import 'dart:io' as Io;

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

class MovieTheaterBody extends StatefulWidget {
  final String encodedBytes;

  const MovieTheaterBody({required this.encodedBytes});

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

class _MovieTheaterBodyState extends State<MovieTheaterBody> {
  late Future<VideoPlayerController> _futureController;
  late VideoPlayerController _controller;

  Future<VideoPlayerController> createVideoPlayer() async {
    try {
      var decodedBytes = base64Decode(widget.encodedBytes);

      var file = Io.File("decodedBezkoder.mp4");
      file.writeAsBytesSync(decodedBytes);

      VideoPlayerController controller = VideoPlayerController.file(file);
      await controller.initialize();
      await controller.setLooping(true);
      return controller;
    } catch (e) {
      print("object0000000");
      print(e);
      return new VideoPlayerController.asset("dataSource");
    }
  }

  @override
  void initState() {
    _futureController = createVideoPlayer();
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Expanded(
        child: FutureBuilder(
          future: _futureController,
          builder: (context, snapshot) {
            //UST: 05/2021 - MovieTheaterBody - id:11 - 2pts - Criação
            if (snapshot.connectionState == ConnectionState.done && snapshot.data != null) {
              _controller = snapshot.data as VideoPlayerController;
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  AspectRatio(
                    aspectRatio: _controller.value.aspectRatio,
                    child: VideoPlayer(_controller),
                  ),
                  const SizedBox(
                    height: 50,
                  ),
                  FloatingActionButton(
                    onPressed: () {
                      setState(() {
                        if (_controller.value.isPlaying) {
                          _controller.pause();
                        } else {
                          // If the video is paused, play it.
                          _controller.play();
                        }
                      });
                    },
                    backgroundColor: Colors.green[700],
                    child: Icon(
                      _controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
                    ),
                  )
                ],
              );
            } else {
              return const Center(child: CircularProgressIndicator());
            }
          },
        ),
      ),
    );
  }
}
