import json
import subprocess
import sys
import os

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])
product_type_id = json_object["product_type_id"]

if product_type_id is None:
    print("Missing required parameters")
    sys.exit(1)

product_type_id = product_type_id["value"]


product_type_ids = {}

def add_product_type_id(product_type_id, product_name, product_color, product_color_characteristics):
    product_type_ids[product_type_id] = {
      "product_id": f"#{product_type_id}",
      "product_name": product_name,
      "product_color": f"Farbe {product_color}",
      "product_color_characteristics": f"({product_color_characteristics})"
    }

add_product_type_id("32420", "Gizmo die Eidechse", "Grün/Blau/Orange", "Glänzend")
add_product_type_id("92784", "Gizmo die Eidechse", "Glitzer Grün", "Seidenmatt")
add_product_type_id("36521", "Charlie das Häschen", "Hellbraun", "Matt")
add_product_type_id("48273", "Charlie das Häschen", "Gold", "Glänzend")
add_product_type_id("71936", "Ruby die Schlange", "Feuerrot", "Glänzend")
add_product_type_id("58324", "Ruby die Schlange", "Rot/Blau", "Glänzend")


def createPdf(sourceHtml, outputPdf):
  command = [
      "google-chrome-stable",
      "--headless",
      "--no-sandbox",
      "--disable-gpu",
      "--print-to-pdf=" + outputPdf,
      "--run-all-compositor-stages-before-draw",
      "--virtual-time-budget=10000",
      sourceHtml,
  ]

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

  if process.returncode != 0:
      print("Error creating PDF")
      print(stderr)
      sys.exit(1)

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

  # replace placeholders in index.js
  p_type_id = product_type_id.split(" ")[0].split("#")[1]

  if p_type_id not in product_type_ids:
    print("Product type not found")
    sys.exit(1)

  print(f"Creating product label for product type #{p_type_id}")

  product = product_type_ids[p_type_id]

  with open("index.js", "r") as file:
    indexjs = file.read()

  indexjs = indexjs.replace("{{PRODUCT_ID}}", product["product_id"])
  indexjs = indexjs.replace("{{PRODUCT_NAME}}", product["product_name"])
  indexjs = indexjs.replace("{{PRODUCT_COLOR}}", product["product_color"])
  indexjs = indexjs.replace("{{PRODUCT_COLOR_CHARACTERISTICS}}", product["product_color_characteristics"])

  with open("index.js", "w") as file:
    file.write(indexjs)

  # create front page  

  createPdf("frontPage.html", "frontOutput.pdf")
  createPdf("backPage.html", "backOutput.pdf")

  utils.merge_pdfs("frontOutput.pdf", "backOutput.pdf", "Produktschilder.pdf")

  utils.clear_workspace(["frontOutput.pdf", "backOutput.pdf", "backPage.html", "frontPage.html", "index.js", "style.css"])