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

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

product_type_id = product_type_id["value"]
label_paper_position = label_paper_position["value"]

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]

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

  with open('../../groupsData/google-sheet-products.json', 'r', encoding='utf-8') as json_file:
    data = json.load(json_file)

  for product in data["products"]:
    if product["id"] == p_type_id:
      with open("index.js", "r") as file:
        indexjs = file.read()

      product_color_characteristics = ""

      if product["product_variant"] != "Farbe":
        product_variant = product["product_variant"] + " " + product["product_color"]
      else:
        product_color_splitted = product["product_color"].split(" ") 

        product_variant = product["product_variant"]  + " " + product_color_splitted[0]
        
        if len(product_color_splitted) > 1:
          product_color_characteristics = product_color_splitted[1]

      indexjs = indexjs.replace("{{PRODUCT_ID}}", product["id"])
      indexjs = indexjs.replace("{{PRODUCT_NAME}}", product["name"])
      indexjs = indexjs.replace("{{PRODUCT_VARIANT}}", product_variant)
      indexjs = indexjs.replace("{{PRODUCT_COLOR_CHARACTERISTICS}}", product_color_characteristics)
      indexjs = indexjs.replace("{{LABEL_PAPER_POSITION}}", label_paper_position)

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

      break

  # create front page  

  createPdf("index.html", "Produktschilder.pdf")

  utils.clear_workspace(["index.html", "index.js"])