import 'dart:math';

import 'package:flutter/material.dart';
import 'dart:ui' as ui;

import 'package:logging/logging.dart';

final Logger _log = Logger('ui_image.dart');

class UIImage extends StatelessWidget {
  final ui.Image image;
  final Size size;

  const UIImage({super.key, required this.image, this.size = Size.infinite});

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: size,
      painter: _UIImagePainter(image: image),
    );
  }
}

class _UIImagePainter extends CustomPainter {
  final ui.Image image;
  _UIImagePainter({required this.image});

  Rect getRect(Rect content, Rect canvas) {
    double scale = min(content.width / canvas.width, content.height / canvas.height);
    Rect rect = Rect.fromLTWH(0, 0, canvas.width * scale, canvas.height * scale);
    Offset offset = content.center - rect.center;
    return rect.shift(offset);
  }

  @override
  void paint(Canvas canvas, Size size) {
    Rect content = Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble());
    Rect canvasRect = Rect.fromLTWH(0, 0, size.width, size.height);

    try {
      canvas.drawImageRect(image, getRect(content, canvasRect), canvasRect, Paint());
    } catch (e) {
      _log.warning(e);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
