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

// linux_spidev was tried out here beforehand,
// but it didn't work well and was replaced by dart_periphery
// import 'package:linux_spidev/linux_spidev.dart';

class MatrixService {
  final spi = SPI(0, 0, SPImode.mode0, 35000);
  // final spidev = Spidev.fromBusDevNrs(0, 0);

  void setLedsOn(List<int> pixels) async {
    // linux_spidev will error out with this console log:
    // flutter: OS Error: Could not open spidev file at "/dev/spidev0.0"
    // Failed to import fence to syncobj: -1

    // Using linux_spidev:
    // try {
    // final handle = spidev.open();
    //   final typedData = Uint8List.fromList(pixels);
    // await handle.transferSingleTypedData(txBuf: typedData, rxBuf: typedData);
    //   handle.close();
    // } catch (e) {
    //   debugPrint(e.toString());
    // }

    // If a tuple error happens with StackTrace? has to be StackTrace:
    // In the source code of spidev.dart line 395, change it to:
    // before:
    // sendPort.send(Tuple3<int, dynamic, StackTrace?>(transferId, null, null));
    // after:
    // sendPort.send(Tuple3<int, dynamic, StackTrace>(transferId, null, StackTrace.current));

    // Using dart_periphery:
    try {
      int refresh = 1;
      while (refresh != 0) {
        spi.transfer(pixels, false);
        await Future.delayed(const Duration(milliseconds: 100));
        refresh--;
      }
    } catch (e) {
      debugPrint(e.toString());
    } finally {
      // clean up the resource
      spi.dispose();
    }
  }
}
