from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from .models import MailSettings
from .serializers import MailSettingsSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django_mailbox.models import Mailbox
from Auth.models import Profile
from django_celery_beat.models import PeriodicTask
import urllib.parse

class MailSettingsView(APIView):
    """
    API pour gérer les paramètres SMTP.
    """

    @swagger_auto_schema(
        operation_description="Récupérer les paramètres SMTP pour un établissement spécifique ou tous les paramètres si aucun ID n'est fourni",
        manual_parameters=[
            openapi.Parameter(
                'establishment_id',
                openapi.IN_QUERY,
                description="ID de l'établissement (facultatif)",
                type=openapi.TYPE_INTEGER,
                required=False
            )
        ],
        responses={
            200: MailSettingsSerializer(many=True),
            404: openapi.Response(description="Aucun paramètre SMTP trouvé."),
            500: openapi.Response(description="Erreur interne du serveur."),
        },
    )
    def get(self, request):
        establishment_id = request.query_params.get('establishment_id')

        try:
            if establishment_id:
                # Récupérer les paramètres SMTP pour un établissement spécifique
                mail_settings = MailSettings.objects.filter(establishment_id=establishment_id).first()
                if not mail_settings:
                    return Response(
                        {'error': f"Aucun paramètre SMTP trouvé pour l'établissement {establishment_id}."},
                        status=status.HTTP_404_NOT_FOUND
                    )
                serializer = MailSettingsSerializer(mail_settings)
                return Response(serializer.data, status=status.HTTP_200_OK)
            else:
                # Récupérer tous les paramètres SMTP
                mail_settings = MailSettings.objects.all()
                if not mail_settings.exists():
                    return Response(
                        {'error': "Aucun paramètre SMTP trouvé."},
                        status=status.HTTP_404_NOT_FOUND
                    )
                serializer = MailSettingsSerializer(mail_settings, many=True)
                # ...dans une vue ou un serializer...
                from N3wtSchool.mailManager import test_mailbox_uri
                import urllib.parse

                imap_user = "anthony.audrey.34@gmail.com"
                imap_password = "cztn wyme odjt lbjt"
                imap_server = "imap.gmail.com"
                imap_port = 993

                encoded_user = urllib.parse.quote(imap_user)
                encoded_password = urllib.parse.quote(imap_password)
                uri = f"imap+ssl://{encoded_user}:{encoded_password}@{imap_server}:{imap_port}"
                if not test_mailbox_uri(uri):
                    print(f'uri : {uri}')
                    return Response({'error': "Connexion IMAP impossible. Vérifiez les paramètres."}, status=status.HTTP_400_BAD_REQUEST)
                # Ensuite, tu peux créer la Mailbox si la connexion est OK
                return Response(serializer.data, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @swagger_auto_schema(
        operation_description="Créer ou mettre à jour les paramètres SMTP pour un établissement spécifique",
        request_body=MailSettingsSerializer,
        responses={
            200: MailSettingsSerializer(),
            400: openapi.Response(description="Données invalides."),
            500: openapi.Response(description="Erreur interne du serveur."),
        },
    )
    def post(self, request):
        data = request.data
        try:
            mail_settings = MailSettings.objects.first()
            if mail_settings:
                serializer = MailSettingsSerializer(mail_settings, data=data)
            else:
                serializer = MailSettingsSerializer(data=data)

            if serializer.is_valid():
                mail_settings_instance = serializer.save()

                # Création de la mailbox pour le profil si profil_id fourni
                profile_id = data.get('profile_id')
                if profile_id:
                    try:
                        profile = Profile.objects.get(id=profile_id)
                        email = mail_settings_instance.mail_user
                        imap_server = mail_settings_instance.imap_server
                        imap_port = mail_settings_instance.imap_port
                        imap_user = mail_settings_instance.mail_user
                        imap_password = mail_settings_instance.mail_password

                        # Encodage du username et du mot de passe pour l'URI IMAP
                        encoded_user = urllib.parse.quote(imap_user)
                        encoded_password = urllib.parse.quote(imap_password)
                        uri = f"imap+ssl://{encoded_user}:{encoded_password}@{imap_server}:{imap_port}"

                        mailbox, created = Mailbox.objects.get_or_create(
                            name=email,
                            defaults={
                                "uri": uri,
                                "from_email": email,
                                "active": True,
                            }
                        )
                        # Associer la mailbox au profil si champ prévu
                        if hasattr(profile, "mailbox"):
                            profile.mailbox = mailbox
                            profile.save()
                    except Profile.DoesNotExist:
                        pass  # Profil non trouvé, on ignore

                return Response(serializer.data, status=status.HTTP_200_OK)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class SyncImapView(APIView):
    def post(self, request):
        sync_imap = request.data.get("sync_imap", False)
        try:
            task = PeriodicTask.objects.get(name='getMail')
            task.enabled = bool(sync_imap)
            task.save()
            return Response({"success": True, "enabled": task.enabled})
        except PeriodicTask.DoesNotExist:
            return Response({"error": "Tâche non trouvée."}, status=status.HTTP_404_NOT_FOUND)