import time
import serial
import os
import requests
from zebrafy import ZebrafyImage

# Configuration for RS232
serial_port = 'COM2' #'/dev/tty.usbserial-1110'  # Replace with the correct COM port
baud_rate = 115200      # Set according to printer settings
parity = serial.PARITY_NONE
data_bits = serial.EIGHTBITS
stop_bits = serial.STOPBITS_ONE
timeout = 1           # Seconds


def download_image_if_not_exists(image_url, local_filename):
    # Check if the image already exists
    if not os.path.exists(local_filename):
        print(f"Image not found locally. Downloading from {image_url}...")

        # Send HTTP request to get the image
        try:
            response = requests.get(image_url, stream=True)
            response.raise_for_status()  # Will raise an exception for non-2xx responses

            # Open the file in binary write mode and save the content
            with open(local_filename, 'wb') as file:
                for chunk in response.iter_content(1024):  # Download the image in chunks
                    file.write(chunk)

            print(f"Image downloaded and saved as {local_filename}")
        except requests.exceptions.RequestException as e:
            print(f"Failed to download image: {e}")
            return None  # Return None if download fails
    else:
        print(f"Image already exists at {local_filename}")

    # Return the absolute path of the image
    absolute_path = os.path.abspath(local_filename)
    return absolute_path

# image_path = "/Users/oguzhangonel/Downloads/red_gmg_logo.jpg"
image_url="https://solmaz.qatrace.com/static/media/solmaz-logo-bg.f276b9e832174846ae1b.png"
local_filename = 'image.jpg'  

image_path = download_image_if_not_exists(image_url, local_filename)
width=200
height=200


with open(image_path, "rb") as image:
     zpl_string = ZebrafyImage(
        image.read(),
        format="Z64",
        invert=True,
        dither=False,
        threshold=128,
        width=300,
        height=300,
        pos_x=570,
        pos_y=500,
        rotation=270,
        string_line_break=80,
        complete_zpl=True,
    ).to_zpl()

cleaned_zpl = zpl_string.lstrip("^XA")
cleaned_zpl = cleaned_zpl.split("^XZ")
cleaned_zpl=cleaned_zpl[0]
print(cleaned_zpl)

    # Resize the image



# Generate ZPL command with resized image


print_data = f"""
^XA

    ^FWR
    ^CF0,60
    ^FO700,20^FD1922^FS

    {cleaned_zpl}

    ^CF0,30
    ^FO525,20^FDLot/Batch #: 12323^FS
    ^FO490,20^FDBest before date: 123123^FS
    ^FO460,20^FD# Pieces: 124214^FS

    ^CF0,35
    ^FO510,470^FDNET WT:1111.11KG^FS
    ^FO470,470^FDNET WT:22.2222LB^FS

    ^FO 320, 40 ^BY 2 ^BC , 110, , , , A ^FD 0100000000012204112501233102000500219178402086 ^FS

    ^CF0,20
    ^FO210,20^FDCreated by: QA Trace^FS

    ^CW1,E:SIMSUN.TTF
    ^FWN
    ^A1R,40,40
    ^CI28
    ^CFJ,45
    ^FO650,20^FDHHHHEY^FS

    ^CW1,E:SIMSUN.TTF
    ^FWN
    ^A1R,40,40
    ^CI28
    ^CFJ,45
    ^FO600,20^FD筛花皮参片(特大) 散装^FS

    ^XZ
"""

try:
    # Open the serial connection
    with serial.Serial(
        port=serial_port,
        baudrate=baud_rate,
        parity=parity,
        bytesize=data_bits,
        stopbits=stop_bits,
        timeout=timeout,
    ) as ser:
        # Send data to the printer
        ser.write(print_data.encode('utf-8'))
        time.sleep(2)  # Wait for 2 seconds to allow the printer to process the command
        ser.close()
        print("Data sent to the printer successfully.")

except serial.SerialException as e:
    print(f"Error communicating with the printer: {e}")


def check_printer_status():
    status_zpl = "^HH"
    try:
        ser = serial.Serial('/dev/tty.usbserial-1110', baudrate=115200, timeout=1)
        ser.write(status_zpl.encode())  # Send the status check command
        time.sleep(1)
        response = ser.read(ser.inWaiting())  # Read any response from the printer
        print(f"Printer Status: {response}")
        ser.close()
    except serial.SerialException as e:
        print(f"Error: Could not communicate with the printer. {e}")
