import logging
from decimal import Decimal
from email.message import EmailMessage
from asyncio import sleep

import aiosmtplib

from src.ezgg_lan_manager.services.ConfigurationService import ConfigurationService
from src.ezgg_lan_manager.types.User import User

logger = logging.getLogger(__name__.split(".")[-1])

class MailingService:
    def __init__(self, configuration_service: ConfigurationService):
        self._configuration_service = configuration_service
        self._config = self._configuration_service.get_mailing_service_configuration()

    async def send_email(self, subject: str, body: str, receiver: str) -> None:
        if self._configuration_service.DEV_MODE_ACTIVE:
            logger.info(f"Skipped sending mail to {receiver} because demo mode is active.")
            logger.info(f"Subject: {subject}")
            logger.info(f"Receiver: {receiver}")
            logger.info(f"Body: {body}")
            await sleep(1)
            return

        try:
            message = EmailMessage()
            message["From"] = self._config.sender
            message["To"] = receiver
            message["Subject"] = subject
            message.set_content(body)

            await aiosmtplib.send(
                message,
                hostname=self._config.smtp_server,
                port=self._config.smtp_port,
                username=self._config.username,
                password=self._config.password
            )
        except Exception as e:
            logger.error(f"Failed to send email: {e}")

    def generate_account_balance_added_mail_body(self, user: User, added_balance: Decimal, total_balance: Decimal) -> str:
        return f"""
        Hallo {user.user_name},
        
        deinem Account wurden {added_balance:.2f} € hinzugefügt. Dein neues Guthaben beträgt nun {total_balance:.2f} €.
        
        Wenn du zu dieser Aufladung Fragen hast, stehen wir dir in unserem Discord Server oder per Mail an {self._configuration_service.get_lan_info().organizer_mail} zur Verfügung.
        
        Liebe Grüße
        Dein {self._configuration_service.get_lan_info().name} Team
        """
