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

from django.core.management.base import BaseCommand

from libra.books.models import BookItem, Office
from libra.utils import UnicodeWriter

DEFAULT_FILENAME = '/var/log/yandex/tools-libra/lost.csv'


class Command(BaseCommand):
    help = u'Export lost books from RedRose, Morozov'

    def handle(self, *args, **options):
        logfile = args[0] if len(args) == 1 else DEFAULT_FILENAME
        office_id = Office.objects.filter(name__contains='Морозов')[0].id

        table = (
            (
                unicode(b.book.id),
                unicode(b.id),
                unicode(b.rfid),
                unicode(b.book.title),
                unicode(b.reg_date),
                unicode(b.cost),
                unicode(last_reader(b)),
            )
            for b in BookItem.objects.filter(
                office__id=office_id,
                location_staff=None,
                shelf__isnull=True
            )
        )

        with open(logfile, 'wb') as f:
            writer = UnicodeWriter(f)
            writer.writerow((
                u'metabook_id',
                u'book_id',
                u'rfid',
                u'title',
                u'reg_date',
                u'cost',
                u'last_known_reader',
            ))
            writer.writerows(table)


def last_reader(book_item):
    s = book_item.readhistory_set
    hist = s.latest('id') if s.exists() else None
    return hist.reader if hist else None
