from datetime import datetime 
from sqlalchemy import or_, select 
from app.crud import smtp 
from sqlalchemy.orm import Session 
from app.database.database import SessionLocal 
from app.schemas import smtp 
from sqlalchemy.orm import Session 
from app.models.smtp import Smtp 
from typing import List

from flask import  request, jsonify, Blueprint
from werkzeug.utils import secure_filename  # Utilisé pour sécuriser le nom du fichier

router = Blueprint('smtp', __name__)
# Dépendance pour la base de données
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
from sqlalchemy import text

def update_smtp(db: Session, smtp_id: int, smtp_data: smtp.SmtpUpdate):
    smtp = db.query(Smtp).filter(Smtp.id == smtp_id).first()

    if not smtp:
        jsonify({"detail": "Smtp non trouvé"}), 404

    smtp.hostname = smtp_data["hostname"]
    smtp.port = smtp_data["port"]
    smtp.sender_email_address = smtp_data["sender_email_address"]
    smtp.username = smtp_data["username"]
    smtp.password = smtp_data["password"]
    smtp.encryption_method = smtp_data["encryption_method"]


    db.commit()
    db.refresh(smtp)
    return smtp
@router.get("/smtp/")
def get_smtp():
    db = next(get_db())
    smtp_list = db.query(Smtp).limit(1)

    # Ajouter category_name manuellement
    response = []
    for smtp in smtp_list:
        response.append({
            "id": smtp.id,
            "hostname": smtp.hostname,
            "port": smtp.port,
            "sender_email_address": smtp.sender_email_address,
            "username": smtp.username,
            "password": smtp.password,
            "encryption_method": smtp.encryption_method
        })
    return response


@router.get("/")
def read_smtp():
    # db = SessionLocal()
    # db = next(get_db())
    return get_smtp()

@router.route("/<int:smtp_id>", methods=["PUT"])
def update_smtps(smtp_id):
    smtp = request.json
    db = next(get_db())
    print(smtp)
    updated_smtp =update_smtp(db, smtp_id, smtp)
    if updated_smtp is None:
        return jsonify({"detail": "Smtp non trouvé"}), 404
    updated_smtp={
        "id": updated_smtp.id,
        "hostname": updated_smtp.hostname,
        "port": updated_smtp.port,
        "sender_email_address": updated_smtp.sender_email_address,
        "username": updated_smtp.username,
        "password": updated_smtp.password,
        "encryption_method": updated_smtp.encryption_method
    }
    return jsonify(updated_smtp)

