import requests
import sys
import json
import qrcode
import subprocess
import sys
import os

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

from libs.utils import utils

# DEFINITIONS

ENDPOINT_URL = "https://devdash.ex.umbach.dev/api/v1/crm"
API_KEY = "uY1DTUog-Iax7-ydc4-dP9V-NON1xsbTGH1I"
QR_CODE_URL = "https://link.shinnex.de/"

# MAIN

headers = {
  "X-Api-Key": API_KEY,
  "Content-Type": "application/json"
}

json_object = json.loads(sys.argv[1])
customerEmail = json_object["customerEmail"]
customerName = json_object["customerName"]
discountCode = json_object["discountCode"]
productUrl = json_object["productUrl"]
orderId = json_object["orderId"]

if (customerEmail is None 
    or orderId is None 
    or customerName is None
    or productUrl is None
    or discountCode is None):
  print("Missing required parameters")
  sys.exit(1)

customerEmail = customerEmail["value"]
customerName = customerName["value"]
discountCode = discountCode["value"]
productUrl = productUrl["value"]
orderId = orderId["value"]


def CreateCrmCustomer():
  response = requests.post(
    url=f"{ENDPOINT_URL}/customer/create",
    headers=headers,
    json={
        "FirstName": customerName,
        "Email": customerEmail,
        "LeadOrigin": "Shopify Customer added by GroupTask",
    })
  
  print(f"CreateCrmCustomer response status code {response.status_code}")

  if response.status_code != 200:
    print(f"CreateCrmCustomer req error {response.status_code}")
    sys.exit(1)

  return response.json()["Id"]


def show_third_voucher(show):
  with open("backPage.html", "r") as file:
    html = file.read()

  if show:
    print("Showing third voucher")
    html = html.replace("SHOW_THIRD_VOUCHER", "block")
  else:
    print("Not showing third voucher") 
    html = html.replace("SHOW_THIRD_VOUCHER", "none")

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

def CheckIfCrmCustomerExists():
  print(f"Checking if customer exists: {customerEmail}")

  response = requests.post(
        url=f"{ENDPOINT_URL}/customer",
        headers=headers,
        json={"Email": customerEmail}  # Hier json verwenden, um JSON-Daten zu senden
    )

  print("CheckIfCrmCustomerExists response status code", response.status_code)

  if response.status_code != 200:
    print(f"CheckIfCrmCustomerExists req error {response.status_code}")
    sys.exit(1)

  customerId = ""
  # only on first purchase we show the third voucher
  thirdVoucher = False

  if response.json() == []:
    print("Customer not found")
    customerId = CreateCrmCustomer()

    thirdVoucher = True
  else:
    if len(response.json()) > 1:
      print("Multiple customers found. Don't know which one to use")
      sys.exit(1)

    customerId = response.json()[0]["Id"]

  show_third_voucher(thirdVoucher)
  CreateCrmActivityLink(customerId=customerId, thirdVoucher=thirdVoucher)
  GetCustomerActivityLinks(customerId=customerId)


def CreateCrmActivityLink(customerId, thirdVoucher):
  print(f"Creating CRM activity link for customer {customerId}")
  
  def req(type, url):
    response = requests.post(
      url=f"{ENDPOINT_URL}/links",
      headers=headers,
      json={
          "CustomerId": customerId,
          "Name": f"Shopify Order #{orderId} - {type}",
          "Url": url
      })

    print(f"CreateCrmActivityLink response status code {response.status_code} for {type}")

    if response.status_code != 200:
      print(f"CreateCrmActivityLink req error {response.status_code}")
      sys.exit(1)

  req("10 % Gutschein", f"https://shinnex.de/discount/{discountCode}?utm_source=order&utm_medium=qrcode&utm_campaign=ordervouchercodes&utm_content=reedemvouchercode")
  req("5 € Gutschein", f"{productUrl}?utm_source=order&utm_medium=qrcode&utm_campaign=ordervouchercodes&utm_content=qualifyforvouchercode")
  
  if thirdVoucher:
    req("10 € Gutschein", f"https://docs.google.com/forms/d/e/1FAIpQLSd2GXFbidzazuQnh_Lf2mgeA1npuwHkWjsdmjrxDmSkDQTfew/viewform?entry.347359844={orderId}")


def create_qrcode(type, id):
  data = f"{QR_CODE_URL}{id}"

  # Generate QR code
  qr = qrcode.QRCode(
      version=1,
      error_correction=qrcode.constants.ERROR_CORRECT_L,
      box_size=10,
      border=0,
  )
  qr.add_data(data)
  qr.make(fit=True)

  # Create an image from the QR Code instance
  img = qr.make_image(fill_color="black", back_color="#fdf8ef")

  # Save image to a file
  img.save(f"./{type}.png")

  # Display the generated QR code image
  #img.show()


def GetCustomerActivityLinks(customerId):
  response = requests.get(
    url=f"{ENDPOINT_URL}/customer/view/{customerId}",
    headers=headers,
  )
  
  print(f"GetCustomerActivityLinks response status code {response.status_code}")

  if response.status_code != 200:
    print(f"GetCustomerActivityLinks req error {response.status_code}")
    sys.exit(1)

  data = response.json()["Links"]

  if len(data) == 0:
    print("No links found")
    sys.exit(1)

  # sort data by creation date

  data = sorted(data, key=lambda x: x["CreatedAt"], reverse=True)

  # find the first link that has a name that starts with "Shopify Order #orderId - price € Gutschein"

  linkGift5 = None
  linkGift10 = None
  linkGift10Percent = None

  for link in data:
    if linkGift5 is None and link["Name"].startswith(f"Shopify Order #{orderId} - 5 € Gutschein"):
      linkGift5 = link
    elif linkGift10 is None and link["Name"].startswith(f"Shopify Order #{orderId} - 10 € Gutschein"):
      linkGift10 = link
    elif linkGift10Percent is None and link["Name"].startswith(f"Shopify Order #{orderId} - 10 % Gutschein"):
      linkGift10Percent = link

  if linkGift5 is None or linkGift10 is None or linkGift10Percent is None:
    print("Gift links not found")
    sys.exit(1)

  create_qrcode("5euro", linkGift5["Id"])
  create_qrcode("10euro", linkGift10["Id"])
  create_qrcode("10percent", linkGift10Percent["Id"])


def ReplaceHtmlVariables():
  print("ReplaceHtmlVariables")

  # replace variables in html file
  # read html file and replace variables

  file = open("frontPage.html", "r")
  html = file.read()
  html = html.replace("{{CUSTOMER_NAME}}", customerName)
  file.close()

  file = open("frontPage.html", "w")
  file.write(html)
  file.close()

  file = open("backPage.html", "r")
  html = file.read()
  html = html.replace("{{DISCOUNT_CODE}}", discountCode)
  file.close()

  file = open("backPage.html", "w")
  file.write(html)
  file.close()


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()

  CheckIfCrmCustomerExists()

  ReplaceHtmlVariables()

  createPdf("frontPage.html", "finalFrontPage.pdf")
  createPdf("backPage.html", "finalBackPage.pdf")

  utils.merge_pdfs('finalFrontPage.pdf', 'finalBackPage.pdf', 'Gutscheine.pdf')

  utils.clear_workspace(["5euro.png", "10euro.png", "10percent.png",
                "frontPage.html", "backPage.html", "finalBackPage.pdf",
                "finalFrontPage.pdf"])