import 'dart:io';
import 'dart:ui';

import 'package:flutter/material.dart';

import '../../data/models/pixel.dart';
import '../../business/service/matrix_service.dart';
import '../../business/utils/find_closest_color_index.dart';

class PixelPainter extends CustomPainter {
  final List<Pixel> pixels;

  PixelPainter({required this.pixels});

  @override
  void paint(Canvas canvas, Size size) {
    const double cellSize = 50;

    if (pixels.isNotEmpty) {
      for (final pixel in pixels) {
        final Offset roundedOffset = Offset(
          (pixel.offset.dx / cellSize).clamp(0, 7).toInt() * cellSize + 25,
          (pixel.offset.dy / cellSize).clamp(0, 7).toInt() * cellSize + 25,
        );

        canvas.drawPoints(
          PointMode.points,
          [roundedOffset / 50],
          Paint()
            ..color = pixel.color
            ..strokeWidth = 1
            ..isAntiAlias = false
            ..strokeJoin = StrokeJoin.round
            ..style = PaintingStyle.stroke,
        );
      }

      // Assuming 'width' represents the width of your matrix (in this case, 8)
      const width = 8;

      List<int> colorIntList = pixels.map((pixel) {
        if (pixel.color.value != 0) return findClosestColorIndex(pixel.color);
        return pixel.color.value;
      }).toList();

      // horizontal mirroring
      List<int> mirroredList = List.generate(64, (index) {
        int row = index ~/ width;
        int reversedCol = width - 1 - (index % width);
        int newIndex = row * width + reversedCol;
        return colorIntList[newIndex];
      });

      // dart periphery is only supported on linux
      if (Platform.isLinux) {
        MatrixService().setLedsOn(mirroredList.reversed.toList());
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
