import socket
import time
import random
from time import sleep
from PIL import Image

IP = "100.65.0.2"
PORT = 5005

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

image = Image.open("/root/pixel/pyjamas.jpg")
width, height = image.size
pixels = image.load()

def to_coord(num):
    yield int(bin(num)[-8:], 2)


def packet(x, y, r, g, b):
    result = bytes([0, 0])
    result += bytes([*to_coord(x), *to_coord(y), r, g, b])
    return result


def imagepacket(x, y, xoff, yoff):
    r, g, b = pixels[x,y]
    return packet(x + xoff, y + yoff, r, g, b)


while True:
    xoff, yoff = random.randint(0, 1500), random.randint(0, 1000)
    xoff = yoff = 0
    packets = [imagepacket(x, y, xoff, yoff)
               for x in range(width)
               for y in range(height)]
    random.shuffle(packets)
    print(f"Drawing at {xoff}x{yoff}")

    for p in packets:
        sock.sendto(p, (IP, PORT))

    sleep(15)
