import json
import subprocess
import sys
from PIL import Image
import os

from pdf2image import convert_from_path

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))

from libs.utils import utils

json_object = json.loads(sys.argv[1])
shipping_label_url = json_object["shipping_label_url"]
customer_first_name = json_object["customer_first_name"]

if shipping_label_url is None or customer_first_name is None:
    print("Missing required parameters")
    sys.exit(1)

shipping_label_url = shipping_label_url["value"]
customer_first_name = customer_first_name["value"]

def createHighDpiPng(sourceHtml, outputPng):
    # Calculate scaled dimensions
    scale_factor = 2
    width = int(2192 * scale_factor)  # Original width in pixels multiplied by the scale factor
    height = int(386 * scale_factor)  # Original height in pixels multiplied by the scale factor

    command = [
        "google-chrome-stable",
        "--headless",
        "--no-sandbox",
        "--disable-gpu",
        "--screenshot=" + outputPng,
        "--window-size={},{}".format(width, height),  # Set window size to scaled dimensions
        "--force-device-scale-factor={}".format(scale_factor),  # Set device scale factor
        sourceHtml,
    ]

    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    _, stderr = process.communicate()

    if process.returncode != 0:
        print("Error creating PNG")
        print(stderr.decode())  # Decoding the stderr for better readability
        sys.exit(1)

def downloadFilePNG(url, filename):
    command = [
        "curl",
        "-o",
        filename,
        url,
    ]

    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    _, stderr = process.communicate()

    if process.returncode != 0:
        print("Error downloading file")
        print(stderr.decode())  # Decoding the stderr for better readability
        sys.exit(1)

    # use PIL to rotate the image by 90 degrees

    image = Image.open(filename)

    # Rotate the image by 90 degrees

    rotated_image = image.rotate(90, expand=True)

    # Save the rotated image

    rotated_image.save(filename)

def downloadFilePDF(url, filename):
    pdf_filename = filename + ".pdf"

    command = [
        "curl",
        "-L",  # Follow redirects
        "-o",
        pdf_filename,
        url,
    ]

    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate() 

    if process.returncode != 0:
        print("Error downloading file")
        print("STDOUT:")
        print(stdout.decode())  # Decoding the stdout for better readability
        print("STDERR:")
        print(stderr.decode())  # Decoding the stderr for better readability
        sys.exit(1)

    # Convert the PDF to a PNG
    images = convert_from_path(pdf_filename, dpi=300)

    page = images[0]
 
    h = page.height/2
    spacing = 250

    # box=(left, upper, right, lower)
    page.crop((0, spacing, page.width, h-spacing)
                ).save(filename, 'PNG')

def downloadFilePDFDHL(url, filename):
    pdf_filename = filename + ".pdf"

    command = [
        "curl",
        "-L",  # Follow redirects
        "-o",
        pdf_filename,
        url,
    ]

    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate() 

    if process.returncode != 0:
        print("Error downloading file")
        print("STDOUT:")
        print(stdout.decode())  # Decoding the stdout for better readability
        print("STDERR:")
        print(stderr.decode())  # Decoding the stderr for better readability
        sys.exit(1)

    # Convert the PDF to a PNG
    images = convert_from_path(pdf_filename, dpi=300)

    page = images[0]

    # box=(left, upper, right, lower)
    #page.crop((0, spacing, page.width, h-spacing)).save(filename, 'PNG')
    page.rotate(90, expand=1).save(filename, 'PNG')


def replacePlaceholder():
    with open("index.html", "r") as file:
      index_html = file.read()

    index_html = index_html.replace("{{CUSTOMER_FIRST_NAME}}", customer_first_name)

    with open("index.html", "w") as file:
      file.write(index_html)


if __name__ == "__main__":
    utils.move_files_back_from_old_files()

    print(f"Creating package label for {customer_first_name}")

    #if shipping_label_url contains  .pdf, download the file and convert it to a PNG
    if "247f81-22.myshopify.com" in shipping_label_url:
        downloadFilePDFDHL(shipping_label_url, "label.png")
    elif ".pdf" in shipping_label_url or "https://cloud.umbach.dev/" in shipping_label_url:
        downloadFilePDF(shipping_label_url, "label.png")
    else:
        downloadFilePNG(shipping_label_url, "label.png")

    replacePlaceholder()
    
    createHighDpiPng("index.html", "Versandlabel.png")

    utils.clear_workspace(["index.html", "label.png.pdf", "label.png"])    
