# Path: web/util/db.py
# def get_db(database=None):


from web.util.db import db
        from feed import Feed

    @classmethod
    def get_unread_counter_by_user_feedsite(cls,user=None,feedsite=None):
        sub = cls.objects(user=user,feedsite=feedsite).only("unread_counter").first()
        if sub:
            return sub.unread_counter
        return 0

    @classmethod
    def add_sub(cls,user,feedsite):
        sub = cls(user=user,feedsite=feedsite)
        sub.user = user
        sub.feedsite = feedsite
        temp = feedsite.feed_item_counter
        
        # sub.start_date = feedsite.get_last_feed(skip=sub.unread_counter-1).create_date
        

        feeds = Feed.get_feed_items_by_site(site=feedsite,
                                              limit=temp)
        for feed in feeds[:500]:
            if not user.has_feed(feed=feed):
                ReadFeed.add(feed=feed,user=user,feedsite=feedsite)
                sub.unread_counter += 1
        sub.save()
        return sub


    @classmethod
    def exist_sub(cls,user=None,feedsite=None):

# Path: web/util/db.py
# def get_db(database=None):


# Path: web/model/user_feed.py
from web.util.db import db
        from feed import Feed


    @classmethod
    def get_unread_counter_by_user_feedsite(cls,user=None,feedsite=None):
        sub = cls.objects(user=user,feedsite=feedsite).only("unread_counter").first()
        if sub:
            return sub.unread_counter
        return 0

    @classmethod
    def add_sub(cls,user,feedsite):
        sub = cls(user=user,feedsite=feedsite)
        sub.user = user
        sub.feedsite = feedsite
        temp = feedsite.feed_item_counter
        
        # sub.start_date = feedsite.get_last_feed(skip=sub.unread_counter-1).create_date
        

        feeds = Feed.get_feed_items_by_site(site=feedsite,
                                              limit=temp)
        for feed in feeds[:500]:
            if not user.has_feed(feed=feed):
                ReadFeed.add(feed=feed,user=user,feedsite=feedsite)
                sub.unread_counter += 1
        sub.save()
        return sub


    @classmethod
    def exist_sub(cls,user=None,feedsite=None):

        return cls.objects(user=user,feedsite=feedsite).first() is not None