from flask import Flask, render_template, request, redirect, url_for, session, flash, send_file, jsonify
import sqlite3
from datetime import datetime
from io import BytesIO
from fpdf import FPDF
import time
import socket
import threading
import queue
import json
import logging
from user_management import user_manager

# Logging ayarları
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# Flask HTTP request loglarını kapat
logging.getLogger('werkzeug').setLevel(logging.WARNING)

# Font subsetting loglarını kapat (PDF oluştururken spam yapıyor)
logging.getLogger('fontTools.subset').setLevel(logging.WARNING)
logging.getLogger('fontTools').setLevel(logging.WARNING)

app = Flask(__name__)
app.secret_key = 'çok-gizli-bir-anahtar'

# Global TCP Manager instance - tcp_manager.py'den import edilecek
from tcp_manager import tcp_manager

def get_db_connection():
    conn = sqlite3.connect('data.db')
    conn.row_factory = sqlite3.Row
    return conn

def get_locale():
    return session.get('dil', 'tr')

def _(key):
    lang = get_locale()
    return TRANSLATIONS.get(lang, TRANSLATIONS['tr']).get(key, key)

@app.context_processor
def inject_translations():
    return dict(_=_)

# Çeviri sözlükleri - translations.py'den import edilecek
from translations import TRANSLATIONS

def init_deviceinfo_table():
    """Deviceinfo tablosunu oluştur"""
    conn = get_db_connection()
    conn.execute('''
        CREATE TABLE IF NOT EXISTS deviceinfo (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            device_id TEXT NOT NULL,
            ip_address TEXT,
            firmware_version TEXT,
            last_update DATETIME DEFAULT CURRENT_TIMESTAMP,
            device_data TEXT,
            status TEXT DEFAULT 'unknown'
        )
    ''')
    conn.commit()
    conn.close()

# Route'ları import et ve başlat
from routes import init_routes
init_routes(app)

if __name__ == '__main__':
    # Gerekli tabloları oluştur
    init_deviceinfo_table()
    
    try:
        tcp_manager.start_server(port=5002)
        logger.info("TCP Server başlatıldı - Port 5002")
    except Exception as e:
        logger.error(f"TCP Server başlatma hatası: {e}")
    
    logger.info("Uygulama başlatılıyor...")
    app.run(host='0.0.0.0', port=5001, debug=False, use_reloader=False, threaded=False) 