import 'dart:typed_data';

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

class LiveStream extends StatefulWidget {
  final String url;

  LiveStream({required this.url});

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

class _LiveStreamState extends State<LiveStream> {
  WebSocketChannel? _channel;
  ImageProvider? _currentFrame;

  @override
  void initState() {
    super.initState();
    _connectToWebSocket();
  }

  @override
  void dispose() {
    _channel?.sink.close();
    super.dispose();
  }

  void _connectToWebSocket() {
    final wsUrl = Uri.parse(widget.url);
    var channel = WebSocketChannel.connect(wsUrl);

    channel.stream.listen(
      (message) {
        final Uint8List byteData = message;
        setState(() {
          _currentFrame = MemoryImage(byteData);
        });
      },
      onError: () {
        print("error");
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return _currentFrame != null
        ? Image(
            image: _currentFrame!,
            gaplessPlayback: true,
          )
        : CircularProgressIndicator();
  }
}
