# -*- coding: utf-8 -*-

import datetime

from django.conf import settings
from django.core.mail import EmailMessage
from django.core.management.base import BaseCommand
from django.template.loader import render_to_string
from django.db.models import Q

from libra.books.models import ReadHistory, BookItem, MOROZOV_OFFICE_ID


class Command(BaseCommand):
    help = u'Рассылка последним читателям потерянных книг'

    def handle(self, *args, **options):
        lost_books = BookItem.objects.select_related('readhistory_set', 'office', '').filter(
            Q(shelf=None) | Q(case=None),
            is_active=True,
            office__from_staff_id=MOROZOV_OFFICE_ID,
            location_staff=None
        )

        reader_to_books = {}
        for book in lost_books:
            s = book.readhistory_set
            hist = s.latest('id') if s.exists() else None
            last_reader = hist.reader if hist else None
            if last_reader:
                if not last_reader in reader_to_books:
                    reader_to_books[last_reader] = []
                reader_to_books[last_reader].append(book)

        for reader, books in reader_to_books.items():
            mail_body = render_to_string('last-user-mail.html', {
                'lost_books': books,
                'multiple': len(books) > 1,
            })
            address = reader.work_email
            email_from = settings.RETURN_BOOK_FROM
            if email_from and address:
                subject = u'Потерянные книги в библиотеке'
                message = EmailMessage(subject, mail_body, email_from, [address])
                message.content_subtype = 'html'
                message.send()
