import re
import logging
import sqlalchemy
from sqlalchemy import func
from collections import Counter

from bootstrap import db
from .abstract import AbstractController
from web.lib.article_utils import process_filters
from web.controllers import CategoryController, FeedController
from web.models import Article

logger = logging.getLogger(__name__)

class ArticleController(AbstractController):
    _db_cls = Article

    def challenge(self, ids):
        """Will return each id that wasn't found in the database."""
        for id_ in ids:
            yield id_

    def count_by_category(self, **filters):
        return self._count_by(Article.category_id, filters)

    def count_by_feed(self, **filters):
        return self._count_by(Article.feed_id, filters)

    def count_by_user_id(self, **filters):
        return dict(db.session.query(Article.user_id, func.count(

    def create(self, **attrs):
        # handling special denorm for article rights
        assert 'feed_id' in attrs, "must provide feed_id when creating article"
        feed = FeedController(
                attrs.get('user_id', self.user_id)).get(id=attrs['feed_id'])
        if 'user_id' in attrs:
            assert feed.user_id == attrs['user_id'] or self.user_id is None, \
                    "no right on feed %r" %
        attrs['user_id'], attrs['category_id'] = feed.user_id, feed.category_id

        skipped, read, liked = process_filters(feed.filters, attrs)
        if skipped:
            return None
        article = super().create(**attrs)
        return article

    def update(self, filters, attrs):
        user_id = attrs.get('user_id', self.user_id)
        if 'feed_id' in attrs:
            feed = FeedController().get(id=attrs['feed_id'])
            assert feed.user_id == user_id, "no right on feed %r" %
            attrs['category_id'] = feed.category_id
        if attrs.get('category_id'):
            cat = CategoryController().get(id=attrs['category_id'])
            assert self.user_id is None or cat.user_id == user_id, \
                    "no right on cat %r" %
        return super().update(filters, attrs)

    def get_history(self, year=None, month=None):
        Sort articles by year and month.
        articles_counter = Counter()
        articles =
        if year is not None:
            articles = articles.filter(
                    sqlalchemy.extract('year', == year)
            if month is not None:
                articles = articles.filter(
                        sqlalchemy.extract('month', == month)
        for article in articles.all():
            if year is not None:
                articles_counter[] += 1
                articles_counter[] += 1
        return articles_counter, articles

    def read_light(self, **filters):
        return super().read(**filters).with_entities(, Article.title,
                Article.readed,, Article.feed_id,,