import 'dart:ui' as ui;

import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';


class TextureVideoView extends StatelessWidget {
  const TextureVideoView({
    super.key,
    required this.textureId,
    required this.textureVersion,
    required this.videoSize,
    required this.fit,
  });

  final ValueListenable<int?> textureId;
  final ValueListenable<int> textureVersion;
  final ValueListenable<ui.Size?> videoSize;
  final ValueListenable<BoxFit> fit;

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<int?>(
      valueListenable: textureId,
      builder: (context, id, _) {
        if (id == null || id < 0) {
          return const SizedBox.expand();
        }
        return ValueListenableBuilder<int>(
          valueListenable: textureVersion,
          builder: (context, version, _) {
            final texture = Texture(
              key: ValueKey<int>(Object.hash(id, version)),
              textureId: id,
            );
            return ValueListenableBuilder<ui.Size?>(
              valueListenable: videoSize,
              builder: (context, size, _) {
                if (size == null || size.width <= 0 || size.height <= 0) {
                  return texture;
                }
                return ValueListenableBuilder<BoxFit>(
                  valueListenable: fit,
                  builder: (context, fitValue, _) => SizedBox.expand(
                    child: FittedBox(
                      fit: fitValue,
                      clipBehavior: Clip.hardEdge,
                      child: SizedBox(
                        width: size.width,
                        height: size.height,
                        child: texture,
                      ),
                    ),
                  ),
                );
              },
            );
          },
        );
      },
    );
  }
}
