# coding: utf-8
import re
from optparse import make_option

from django.conf import settings
from django.core.management.base import BaseCommand
from ids.registry import registry

from libra.utils import lock
from libra.books.models import Book


class Command(BaseCommand):
    help = u"Склеивает треды в этушке с книжкой"

    option_list = BaseCommand.option_list + (
        make_option('--force', action='store_true', dest='force', default=False,
                    help=(u'Пройтись по всем постам в клубике,'
                          u' а не только по новым')),
    )

    @lock('match_at_id')
    def handle(self, *args, **kwargs):
        def print_info(msg):
            if int(kwargs.get('verbosity', 1)):
                print msg

        rep = registry.get_repository('at', 'post')
        force = kwargs.get('force', False)

        pattern = re.compile(r'lib.yandex-team.ru/(?:books/)?(\d+)')
        for post in rep.getiter({'uid': settings.AT_CLUB_ID}):
            at_id = int(post['id'].split('/')[-1])

            url = (post.get('meta') or {}).get('url', '')

            book_id = pattern.findall(url)
            if not book_id:
                print_info("Can't find book_id in \"%s\"" % url)
                continue
            else:
                book_id = int(book_id[0])

            try:
                book = Book.objects.get(id=book_id)
            except Book.DoesNotExist:
                print_info("Unknown book %s" % book_id)
                continue

            # как только добрались до уже сматченой - прекращаем
            if not force and book.id == book_id:
                print_info("Stop at previous point")
                break

            book.at_id = at_id
            book.save()
