from rgbmatrix import RGBMatrix, RGBMatrixOptions
from PIL import ImageFont, Image, ImageDraw
#from time import sleep

# Das Bild nur speichern. Nicht die LED-Matrix ansteuern.
DEV = False
#DEV = True

matrix = None

MATRIX_HEIGHT = 64
MATRIX_WIDTH = 64
NUMBER_OF_PANELS = 4

class MyMatrix:
  def __init__(self):
    #self.matrix_width = options.cols * options.chain_length
    #self.matrix_height = options.rows

    try:
      #self.font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-ExtraLight.ttf", 18)
      self.font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 18)
      self.large_font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 32)
      #self.large_font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-ExtraLight.ttf", 32)
    except IOError:
      self.font = ImageFont.load_default()
      self.large_font = ImageFont.load_default()

    self.width = MATRIX_WIDTH * NUMBER_OF_PANELS
    self.height = MATRIX_HEIGHT

    if not DEV:
      options = RGBMatrixOptions()
      options.rows = MATRIX_HEIGHT
      options.cols = MATRIX_WIDTH
      options.chain_length = NUMBER_OF_PANELS
      #options.parallel = 1
      #options.hardware_mapping = 'regular'  # change if using Adafruit HAT, e.g. 'adafruit-hat'
      options.gpio_slowdown = 4  # try 2, 4, or even 5
      #options.disable_hardware_pulsing = True
      #options.show_refresh_rate = True
      options.drop_privileges = False
      #options.brightness = 60  # scale down brightness if needed
      #options.pwm_bits = 8      # default 11–12; lower = faster refresh

      self.matrix = RGBMatrix(options=options)

  def show(self, image):
    """Save the image to disk in DEV mode. Or send it to the LED matrix panel."""
    if DEV:
      image.save('image.png')
    elif matrix:
      self.matrix.SetImage(image)
    else:
      print("Not in dev mode. And matrix not initialized.")

  def buffer(self):
    """Get an image buffer with the right dimensions"""
    return Image.new("RGB", (MATRIX_WIDTH * NUMBER_OF_PANELS, MATRIX_HEIGHT))

  def clear(self):
    """Reset the matrix display. Set to black."""
    if DEV:
      # Just fill with black
      image_buffer = self.buffer()
      draw = ImageDraw.Draw(image_buffer)
      draw.rectangle( ((0,0),(self.width-1,self.height-1)), fill=(0,0,0) )
      self.show(image_buffer)
    else:
      # Send reset signal to matrix
      self.matrix.Clear()

matrix = MyMatrix()

