import 'package:flutter/material.dart';
import 'package:wolf_3d_data_types/wolf_3d_data_types.dart';
import 'package:wolf_dart/features/renderer/color_palette.dart';

class WeaponPainter extends CustomPainter {
  final Sprite? sprite;

  // Initialize a reusable Paint object and disable anti-aliasing to keep the
  // pixels perfectly sharp and chunky.
  final Paint _paint = Paint()
    ..isAntiAlias = false
    ..style = PaintingStyle.fill;

  WeaponPainter({required this.sprite});

  @override
  void paint(Canvas canvas, Size size) {
    if (sprite == null) return;

    // Calculate width and height separately in case the container isn't a
    // perfect square
    double pixelWidth = size.width / 64;
    double pixelHeight = size.height / 64;

    for (int x = 0; x < 64; x++) {
      for (int y = 0; y < 64; y++) {
        int colorByte = sprite![x][y];

        if (colorByte != 255) {
          // 255 is our transparent magenta
          _paint.color = ColorPalette.vga[colorByte];

          canvas.drawRect(
            Rect.fromLTWH(
              x * pixelWidth,
              y * pixelHeight,
              // Add a tiny 0.5 overlap to completely eliminate visual seams
              pixelWidth + 0.5,
              pixelHeight + 0.5,
            ),
            _paint,
          );
        }
      }
    }
  }

  @override
  bool shouldRepaint(covariant WeaponPainter oldDelegate) {
    // ONLY repaint if the actual animation frame (sprite) has changed!
    // This saves massive amounts of CPU when the player is just walking around.
    return oldDelegate.sprite != sprite;
  }
}
