# coding: utf-8
from __future__ import unicode_literals

import logging
import datetime
from itertools import groupby
from collections import defaultdict

from django.conf import settings
from django.core import mail

from django.core.management.base import BaseCommand
from django.template.loader import render_to_string

from libra.utils import lock
from libra.books.models import ReadHistory, MOSCOW_OFFICES, SIMFEROPOL_OFFICES


logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = 'Рассылка читателям, задержавшим книги дольше положенного срока'

    def messages(self):
        format_day = datetime.date.today().strftime('%d.%m.%Y')
        subject = 'Отчет о просроченных книгах на %s' % (format_day)
        from_email = settings.RETURN_BOOK_FROM

        history = groupby(
            ReadHistory
            .taken_long_ago()
            .select_related('book_item', 'reader__office')
            .order_by('book_item', '-get_date'),

            lambda x: x.book_item_id
        )

        book_list = defaultdict(list)
        for book_item_id, book_history in history:
            history_item = next(book_history)
            book_list[history_item.reader].append(history_item)

        for reader, books in book_list.items():

            office_id = reader.office.from_staff_id
            if office_id in MOSCOW_OFFICES:
                template = 'returnbook-mail-more.html'
            elif office_id in SIMFEROPOL_OFFICES:
                template = 'returnbook-mail-simferopol.html'
            else:
                continue

            reader_mail = reader.work_email
            if reader_mail:
                body = render_to_string(template, {'return_books': books})

                msg = mail.EmailMessage(
                    subject=subject,
                    body=body,
                    from_email=from_email,
                    to=[reader_mail],
                    bcc=[from_email],
                    headers={'X-Ya-Libra': 'returnbook'},
                )
                msg.content_subtype = "html"

                logger.info('Cron returnbook. Message for %s sended.', reader_mail)
                yield msg

    @lock('returnbook')
    def handle(self, *args, **options):
        logger.info('Cron returnbook started')
        if not settings.RETURN_BOOK_MAIL:
            logging.info('Cron returnbook disabled in settings')
            return

        try:
            connection = mail.get_connection()
            connection.send_messages(self.messages())
        except Exception:
            logger.exception('Error in Cron returnbook')
