"""
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.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
from ...models import SaleList

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


class Command(BaseCommand):
    help = "Send notification to all sale list owners for a delay in the return of articles"

    def handle(self, *args, **options):
        translation.activate(settings.LANGUAGE_CODE)
        messages = []
        current_site = Site.objects.get(pk=1)
        site_name = current_site.name
        domain = current_site.domain
        context = {
            "domain": domain,
            "site_name": site_name,
            "event": get_active_event(),
        }
        for sale_list in SaleList.objects.filter(event=get_active_event()):
            user = sale_list.owner
            context["user"] = user
            context["email"] = user.email
            context["sale_list"] = sale_list

            subject = loader.render_to_string(
                "sale_lists/email/notification_return_article_delay_subject.txt",
                context,
            )
            # Email subject *must not* contain newlines
            subject = "".join(subject.splitlines())
            message = loader.render_to_string(
                "sale_lists/email/notification_return_article_delay_message.html",
                context,
            )
            to = ["{0} <{1}>".format(user.get_full_name(), user.email)]
            mail = EmailMessage(subject, message, settings.SERVER_EMAIL, to)
            messages.append(mail)

        if len(messages) > 0:
            connection = get_connection()
            connection.fail_silently = True
            connection.send_messages(messages)
            print("send {0} delay notifications".format(len(messages)))
