import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:wolf_3d_dart/wolf_3d_data_types.dart';
import 'package:wolf_3d_dart/wolf_3d_engine.dart';
import 'package:wolf_3d_renderer/base_renderer.dart';
import 'package:wolf_3d_renderer/wolf_3d_asset_painter.dart';

class WolfFlutterRenderer extends BaseWolfRenderer {
  const WolfFlutterRenderer({
    required super.engine,
    super.key,
  });

  @override
  State<WolfFlutterRenderer> createState() => _WolfFlutterRendererState();
}

class _WolfFlutterRendererState
    extends BaseWolfRendererState<WolfFlutterRenderer> {
  final FrameBuffer _frameBuffer = FrameBuffer(320, 200);
  final SoftwareRasterizer _rasterizer = SoftwareRasterizer();

  ui.Image? _renderedFrame;
  bool _isRendering = false;

  @override
  Color get scaffoldColor => const Color.fromARGB(255, 4, 64, 64);

  @override
  void performRender() {
    if (_isRendering) return;
    _isRendering = true;

    _rasterizer.render(widget.engine, _frameBuffer);

    ui.decodeImageFromPixels(
      _frameBuffer.pixels.buffer.asUint8List(),
      _frameBuffer.width,
      _frameBuffer.height,
      ui.PixelFormat.rgba8888,
      (ui.Image image) {
        if (mounted) {
          setState(() {
            _renderedFrame?.dispose();
            _renderedFrame = image;
          });
        }
        _isRendering = false;
      },
    );
  }

  @override
  Widget buildViewport(BuildContext context) {
    // If we don't have a frame yet, show the loading state
    if (_renderedFrame == null) {
      return const CircularProgressIndicator(color: Colors.white24);
    }

    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: AspectRatio(
        aspectRatio: 4 / 3,
        child: WolfAssetPainter.frame(_renderedFrame),
      ),
    );
  }
}
