from PIL import Image, ImageDraw, ImageFont
import socket
import binascii
import io
import time
import re
import numpy as np

import PIL.ImageOps



class MatrixSender(object):

    C_BLACK = 0
    C_WHITE = 255

    global threadrunning
    threadrunning=False

    def __init__(self, udphost, udpport, img_size=(160,48), bitsperpixel=1):

        self._udphost = udphost
        if not type(udpport) is int or udpport > 65536:
            raise TypeError('port has to be int and > 65536 !!')
        self._udpport = udpport
        self._img_size = img_size

        self.bitsperpixel=bitsperpixel

        self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    def send(self, image,invert=False):
        global threadrunning
        imgmap = []
        sendbyte=0
        senddata=bytearray()
        pixelofbyte=0
        for pixel in image.getdata():
            r, g, b, a = pixel

            pixelbrightness=int( (r+g+b)/3 *(pow(2,self.bitsperpixel)-1) /255 +0.5)
            sendbyte+=pixelbrightness<<(pixelofbyte*self.bitsperpixel)
            pixelofbyte+=1
            if pixelofbyte>=(8/self.bitsperpixel):
                pixelofbyte=0
                senddata.append(sendbyte)
                sendbyte=0

        self._sock.sendto(bytes(senddata), (self._udphost, self._udpport))
