"""
This file is part of the Tetris project.

Written 2023 by Maarten Tromp <maarten@geekabit.nl>


Website
-------
https://www.geekabit.nl/projects/tetris-window/


License
-------
CC0 (no copyright, public domain)
The person who associated a work with this deed has dedicated the work to the public domain by
waiving all of his or her rights to the work worldwide under copyright law, including all related
and neighbouring rights, to the extent allowed by law. You can copy, modify, distribute and perform
the work, even for commercial purposes, all without asking permission.
https://creativecommons.org/share-your-work/public-domain/cc0/
"""


# imports
import logging
import board
import neopixel


class Led:
	"""
	Simple Led class that handles writing to neopixels connected to GPIO.
	"""


	def __init__(self, width, height):
		"""
		Initialized led class

		Parameters
		----------
		width, height: number
			Display dimensions.

		Returns
		-------
		none
		"""

		logging.debug("led matrix init")

		# private variables
		self._width = width
		self._height = height
		# connect leds to GPIO10 (physical pin 19)
		self._pixels = neopixel.NeoPixel(board.D10, self._width * self._height,
				auto_write = False)


#	def write(self, buf, dim = 1):
	def write(self, buf):
		"""
		Write buffer buffer to leds.

		Parameters
		----------
		buf: tuple or list
			3-dimensional list of rows, cells and RGB values.
		dim: float [0..1]
			Multiplication "dimming" value for led brightness. Default: 1.

		Returns
		-------
		none
		"""

#		assert 0 <= dim <= 1, f"invalid dim: {dim}"
		assert len(buf) == self._height, f"invalid height in buf: {buf}"

		# rotate display 180 degrees because of the way pixels are wired
		led_counter = self._width * self._height - 1
		for row in buf:
			assert len(row) == self._width, f"invalid width in buf: {buf}"
			for pixel in row:
				assert len(pixel) == 3, f"invalid pixel in buf: {buf}"
#				dimmed = tuple(round(val * dim) for val in pixel)
#				self._pixels[led_counter] = dimmed
				self._pixels[led_counter] = pixel
				led_counter -= 1

		self._pixels.show()


	def clear(self):
		"""
		Clear all leds.

		Parameters
		----------
		none

		Returns
		-------
		none
		"""

		self._pixels.fill((0, 0, 0))
		self._pixels.show()
