import logging
import uuid
import re

from feedformatter import Feed
import time

from scribeengine.lib.base import *
from scribeengine.model.meta import Session
from scribeengine.model import Post, Variable

log = logging.getLogger(__name__)

class FeedController(BaseController):

    def _generate_feed(self):
        blog_title = Session.query(Variable).get(u'blog title').value
        blog_slogan = Session.query(Variable).get(u'blog slogan').value
        blog_link = str('%s://%s' % (request.environ[u'wsgi.url_scheme'], \
                                     request.environ[u'HTTP_HOST']))
        if blog_link.endswith(u'/'):
            blog_link = blog_link[:-1]
        posts = Session.query(Post)\
            .filter_by(status=u'published')\
            .order_by(Post.created.desc())\
            .all()
        # Create the feed
        feed = Feed()
        # Set the feed/channel level properties
        feed.feed[u'title'] = blog_title
        feed.feed[u'link'] = blog_link + u'/'
        feed.feed[u'description'] = blog_slogan
        for post in posts:
            # Create an item
            item = {}
            item[u'title'] = post.title
            item[u'link'] = blog_link + h.url_for_post(post)
            item[u'author'] = post.user.nick
            item[u'description'] = re.sub(r'<(.*?)>', u'', h.teaser(post.body))
            item[u'pubDate'] = post.created.timetuple()
            item[u'guid'] = str(uuid.uuid5(uuid.NAMESPACE_URL, blog_link + h.url_for_post(post)))
            # Add item to feed
            feed.items.append(item)
        return feed

    def index(self):
        h.redirect_to(h.url_for(action=u'atom'))

    def rss(self, id=u'2.0'):
        feed = self._generate_feed()
        if id == u'1.0':
            return feed.format_rss1_string()
        else:
            return feed.format_rss2_string()

    def atom(self):
        feed = self._generate_feed()
        return feed.format_atom_string()