import requests
from PIL import Image, ImageDraw, ImageFont

dither = 0                         # set dither to 1 if you're sending photos etc.
apip = "192.168.0.199"          # IP address of your access point
mac_file = "macs.txt"             # Textdatei mit einer MAC pro Zeile

# Create a new paletted image with indexed colors
image = Image.new('P', (296, 152))

# Define the color palette (white, black, red)
palette = [
    255, 255, 255,  # white
    0, 0, 0,        # black
    255, 0, 0       # red
]
image.putpalette(palette)

# Initialize the drawing context
draw = ImageDraw.Draw(image)

# Define the text lines
line1 = 'termux-wiper'
line2 = 'seems working???'

# Define the fonts and sizes
font_line1 = ImageFont.truetype('arial.ttf', size=36)
font_line2 = ImageFont.truetype('arial.ttf', size=16)

# Calculate the text bounding boxes to get the text widths and heights
text_bbox_line1 = draw.textbbox((0, 0), line1, font=font_line1)
text_bbox_line2 = draw.textbbox((0, 0), line2, font=font_line2)

# Calculate the text positions to center the lines horizontally
text_position_line1 = ((image.width - (text_bbox_line1[2] - text_bbox_line1[0])) // 2, 20)
text_position_line2 = ((image.width - (text_bbox_line2[2] - text_bbox_line2[0])) // 2, 80)

# Write the text on the image (palette index 2 = red, index 1 = black)
draw.text(text_position_line1, line1, fill=2, font=font_line1)  # red
draw.text(text_position_line2, line2, fill=1, font=font_line2)  # black

# Convert the image to 24-bit RGB
rgb_image = image.convert('RGB')

# Save the image as JPEG with maximum quality
image_path = 'output.jpg'
rgb_image.save(image_path, 'JPEG', quality="maximum")

# Prepare the HTTP POST request
url = "http://" + apip + "/imgupload"

# MAC-Adressen aus der Datei lesen (eine pro Zeile, Leerzeilen werden übersprungen)
with open(mac_file, "r", encoding="utf-8") as f:
    mac_list = [line.strip() for line in f if line.strip()]

# Für jede MAC-Adresse den gleichen Upload durchführen
for mac in mac_list:
    payload = {"dither": dither, "mac": mac}
    with open(image_path, "rb") as file:
        response = requests.post(url, data=payload, files={"file": file})
    # Ergebnis pro MAC-Adresse ausgeben
    if response.status_code == 200:
        print(f"Image uploaded successfully to {mac}!")
    else:
        print(f"Failed to upload the image to {mac}.")