"""
Second-Hand-Shop Project

@author:     Malte Gerth
@copyright:  Copyright (C) 2015 Malte Gerth
@license:    MIT
@maintainer: Malte Gerth
@email:      mail@malte-gerth.de
"""

from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.sites.models import Site
from django.core.mail import get_connection, EmailMessage
from django.core.management import BaseCommand
from django.template import loader
from django.utils import translation

from events.models import get_active_event

__author__ = "Malte Gerth <mail@malte-gerth.de>"
__copyright__ = "Copyright (C) 2015 Malte Gerth"
__license__ = "MIT"


class Command(BaseCommand):
    help = (
        'Send an e-amil to all users using the template "send_newsletter_message.html"'
    )

    def handle(self, *args, **options):
        translation.activate(settings.LANGUAGE_CODE)
        messages = []
        current_site = Site.objects.get(pk=1)
        context = {
            "domain": current_site.domain,
            "site_name": current_site.name,
            "event": get_active_event(),
        }
        users = get_user_model().objects.filter(is_active=True)
        for user in users:
            context["user"] = user
            context["email"] = user.email
            subject = loader.render_to_string(
                "secondhandshop_server/email/send_newsletter_subject.txt", context
            )
            # Email subject *must not* contain newlines
            subject = "".join(subject.splitlines())
            message = loader.render_to_string(
                "secondhandshop_server/email/send_newsletter_message.html", context
            )
            mail = EmailMessage(
                subject,
                message,
                settings.SERVER_EMAIL,
                ["{0} <{1}>".format(user.get_full_name(), user.email)],
            )
            messages.append(mail)

        if len(messages) > 0:
            connection = get_connection()
            connection.fail_silently = True
            connection.send_messages(messages)
