from flask import Flask, jsonify, request
import requests
import sqlite3
from dotenv import load_dotenv
import os

load_dotenv()
printers = os.getenv('PRINTER_IPS').split(',')

app = Flask(__name__)

# SQLite-Datenbank initialisieren
def init_db():
    conn = sqlite3.connect('printers.db')
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS printers
                 (ip TEXT PRIMARY KEY, status TEXT)''')
    for printer_ip in printers:
        c.execute("INSERT OR IGNORE INTO printers (ip, status) VALUES (?, ?)", (printer_ip, "frei"))
    conn.commit()
    conn.close()

@app.route('/printer_status', methods=['GET'])
def get_printer_status():
    printer_status = []
    conn = sqlite3.connect('printers.db')
    c = conn.cursor()
    
    for printer_ip in printers:
        c.execute("SELECT status FROM printers WHERE ip = ?", (printer_ip,))
        status = c.fetchone()[0]
        
        try:
            response = requests.get(f"http://{printer_ip}/api/printer/status")
            
            if response.status_code == 200:
                status_data = response.json()
                printer_status.append({
                    "ip": printer_ip,
                    "status": status,
                    "progress": status_data["progress"],
                    "temperature": status_data["temperature"]
                })
            else:
                printer_status.append({
                    "ip": printer_ip,
                    "status": "Fehler bei der Abfrage",
                    "progress": None,
                    "temperature": None
                })
        except:
            printer_status.append({
                "ip": printer_ip,
                "status": "Drucker nicht erreichbar",
                "progress": None,
                "temperature": None
            })
    
    conn.close()
    return jsonify(printer_status)

@app.route('/print_job', methods=['POST'])
def submit_print_job():
    print_job = request.json
    printer_ip = print_job["printer_ip"]
    file_url = print_job["file_url"]
    
    conn = sqlite3.connect('printers.db')
    c = conn.cursor()
    c.execute("SELECT status FROM printers WHERE ip = ?", (printer_ip,))
    status = c.fetchone()[0]
    
    if status == "frei":
        try:
            response = requests.post(f"http://{printer_ip}/api/print_job", json={"file_url": file_url})
            
            if response.status_code == 200:
                c.execute("UPDATE printers SET status = 'besetzt' WHERE ip = ?", (printer_ip,))
                conn.commit()
                conn.close()
                return jsonify({"message": "Druckauftrag gestartet"}), 200
            else:
                conn.close()
                return jsonify({"message": "Fehler beim Starten des Druckauftrags"}), 500
        except:
            conn.close()
            return jsonify({"message": "Drucker nicht erreichbar"}), 500
    else:
        conn.close()
        return jsonify({"message": "Drucker ist nicht frei"}), 400

if __name__ == '__main__':
    init_db()
    app.run(host='0.0.0.0', port=5000)
