import requests
import cairosvg
from PIL import Image
import mysql.connector
import sys

max_apriltag_value = 48714

table_name = "data"
id_to_update = "apriltag"

conn = mysql.connector.connect(
    host="localhost",
    port="50035",
    user="ad-internalstuff",
    password="cdQK4pfr3_YfnE1u",
    database="ad-internalstuff"
)

# create table if not exists
create_table_query = f"CREATE TABLE IF NOT EXISTS {table_name} (id VARCHAR(255) PRIMARY KEY, value INT)"

cursor = conn.cursor()
cursor.execute(create_table_query)
cursor.close()

# get current value
select_query = f"SELECT value FROM {table_name} WHERE id = %s"

cursor = conn.cursor()
cursor.execute(select_query, (id_to_update,))
result = cursor.fetchone()

db_value = 0

if result:
    db_value = result[0]
else:
    # value does not exist, create it
    insert_query = f"INSERT INTO {table_name} (id, value) VALUES (%s, %s)"

    cursor = conn.cursor()
    cursor.execute(insert_query, (id_to_update, 0))
    conn.commit()

# check if max value is reached
if db_value >= max_apriltag_value:
    print(f"Max value of {max_apriltag_value} reached.")
    sys.exit(1)

# update value
update_query = f"UPDATE {table_name} SET value = value + %s WHERE id = %s"

db_value += 1

cursor = conn.cursor()
cursor.execute(update_query, (1, id_to_update))
conn.commit()

# close connection to database
cursor.close()
conn.close()

# image handling
new_file_number = str(db_value).zfill(5)

print(f"April Tag number: {db_value}")

svg_url = f"https://git.ex.umbach.dev/Alex/apriltag-chaitanyantr/raw/branch/main/tagStandard52h13/tag52_13_{new_file_number}.svg"

# Fordere das SVG-Bild von der URL an
response = requests.get(svg_url)

if response.status_code == 200:
    try:
        # Speichere das SVG-Bild in einer Datei
        svg_file_name = "apriltag.svg"
        with open(svg_file_name, "wb") as svg_file:
            svg_file.write(response.content)

        # Konvertiere das SVG-Bild in ein PNG-Bild
        png_data = cairosvg.svg2png(bytestring=response.content)

        # Speichere das PNG-Bild in einer Datei
        png_file_name = "apriltag.png"
        with open(png_file_name, "wb") as png_file:
            png_file.write(png_data)

    except Exception as e:
        print("Fehler beim Verarbeiten des Bildes:", str(e))
        sys.exit(1) 
else:
    print("Fehler beim Herunterladen des SVG-Bildes. Statuscode:", response.status_code)
    sys.exit(1)