# coding: utf-8
""" Перевозим обложки с файловой системы в эллиптикс

Читаем файл с метаданными и загружаем картинки в элиптикс
"""

import os
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from libra.books.models import BookCover


class Command(BaseCommand):
    help = (u"Load covers to elliptics\n"
            "Usage: libra covers2elliptics <path/to/covers/>")

    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Usage: libra covers2elliptics <path/to/covers/>")

        path_to_files = args[0]

        with open(os.path.join(path_to_files, 'covers.txt')) as input:
            for line in input:
                if line:
                    id_, imname = line.split()
                    try:
                        cover = BookCover.objects.get(id=int(id_))
                        cover.download(os.path.join(path_to_files, imname),
                                       int(id_))
                        print imname, '\tDone'
                    except Exception:
                        print "cant load %s %s" % (id_, imname)
