# coding: utf-8
from datetime import datetime
from itertools import groupby
from django.core.management.base import BaseCommand
from django.core.mail import EmailMessage
from django.template.loader import render_to_string
from django.conf import settings

from libra.books.models import (BookItem, BookQueue,
                                MOSCOW_OFFICES_IDS, SPB_OFFICES_IDS)
from libra.utils import lock


def groupper_by_office(bq):
    for ids in (MOSCOW_OFFICES_IDS, SPB_OFFICES_IDS):
        if bq.user.office_id in ids:
            return ids[0]

    return bq.user.office_id


class Command(BaseCommand):
    help = u"Посылает уведомления о том что интересующую книгу вернули"

    @lock('enqueue')
    def handle(self, *args, **options):
        bqs = BookQueue.objects.select_related('user', 'book').filter(
            finished=False).order_by('book', 'user__office', 'created_at')

        for book_id, bqs_by_books in groupby(bqs, key=lambda x: x.book_id):
            bqs_by_books = list(bqs_by_books)
            for office_id, bqs_by_office in groupby(bqs_by_books,
                                                    key=groupper_by_office):
                bq = next(bqs_by_office) # берем первого из каждого офиса

                available = BookItem.objects.filter(book=book_id,
                                                    office_id=office_id,
                                                    location_staff=None,
                                                    is_active=True).exists()

                if available:
                    send_letter(bq)
                    bq.finished_at = datetime.now()
                    bq.finished = True
                    bq.save()


def send_letter(book_queue):
    body = render_to_string('book_queue_letter.html',
                            {'user': book_queue.user, 'book': book_queue.book})
    subj = u'В библиотеке появилась книга на которую вы подписаны'
    email_from = settings.RETURN_BOOK_FROM
    msg = EmailMessage(subj, body, email_from, [book_queue.user.work_email])
    msg.content_subtype = "html"

    if settings.RETURN_BOOK_MAIL:
        msg.send()
