# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import feedparser
import HTMLParser

from django.views.decorators.cache import cache_page
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseNotFound, HttpResponseServerError
from django.conf import settings


@cache_page(60 * 60 * 24) # Cache 24h
def feed(request, feed_name):
    feeds = settings.FEEDS
    feed = None
    # Recherce le flux passé en paramètre dans les flux définis dans settings
    for feed_search in feeds:
        if (feed_search[0] == feed_name):
            feed = feed_search
            break

    # Si le flux n'a pas été trouvé ou qu'il n'y a pas d'URL donnée, renvoi 404
    if not feed or len(feed)<2 or not feed[1]:
        return HttpResponseNotFound('')
    # Sinon récupère les informations (url et limit)
    else:
        feed_url = feed[1]
        if len(feed) >=3:
            limit = feed[2]
        else:
            limit = 3

    try:
        feed = feedparser.parse(feed_url)
        entries = feed.entries[:limit]

        return render_to_response('fragments/feed.html',
                                  {'feed_entries': entries},
                                  context_instance=RequestContext(request))
    except:
        return HttpResponseServerError('')
