import datetime
import warnings
from xml.dom import minidom

from django.contrib.syndication import views
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from django.utils import tzinfo
from django.utils.feedgenerator import rfc2822_date, rfc3339_date

from models import Entry


class FeedTestCase(TestCase):
    fixtures = ['feeddata.json']

    def assertChildNodes(self, elem, expected):
        actual = set([n.nodeName for n in elem.childNodes])
        expected = set(expected)
        self.assertEqual(actual, expected)

    def assertChildNodeContent(self, elem, expected):
        for k, v in expected.items():
            self.assertEqual(
                elem.getElementsByTagName(k)[0].firstChild.wholeText, v)

    def assertCategories(self, elem, expected):
        self.assertEqual(set(i.firstChild.wholeText for i in elem.childNodes if i.nodeName == 'category'), set(expected))

######################################
# Feed view
######################################

class SyndicationFeedTest(FeedTestCase):
    """
    Tests for the high-level syndication feed framework.
    """
    urls = 'regressiontests.syndication.urls'

    def test_rss2_feed(self):
        """
        Test the structure and content of feeds generated by Rss201rev2Feed.
        """
        response = self.client.get('/syndication/rss2/')
        doc = minidom.parseString(response.content)

        # Making sure there's only 1 `rss` element and that the correct
        # RSS version was specified.
        feed_elem = doc.getElementsByTagName('rss')
        self.assertEqual(len(feed_elem), 1)
        feed = feed_elem[0]
        self.assertEqual(feed.getAttribute('version'), '2.0')

        # Making sure there's only one `channel` element w/in the
        # `rss` element.
        chan_elem = feed.getElementsByTagName('channel')
        self.assertEqual(len(chan_elem), 1)
        chan = chan_elem[0]

        # Find the last build date
        d = Entry.objects.latest('date').date
        ltz = tzinfo.LocalTimezone(d)
        last_build_date = rfc2822_date(d.replace(tzinfo=ltz))

        self.assertChildNodes(chan, ['title', 'link', 'description', 'language', 'lastBuildDate', 'item', 'atom:link', 'ttl', 'copyright', 'category'])
        self.assertChildNodeContent(chan, {
            'title': 'My blog',
            'description': 'A more thorough description of my blog.',
            'link': 'http://example.com/blog/',
            'language': 'en',
            'lastBuildDate': last_build_date,
            #'atom:link': '',
            'ttl': '600',
            'copyright': 'Copyright (c) 2007, Sally Smith',
        })
        self.assertCategories(chan, ['python', 'django'])

        # Ensure the content of the channel is correct
        self.assertChildNodeContent(chan, {
            'title': 'My blog',
            'link': 'http://example.com/blog/',
        })

        # Check feed_url is passed
        self.assertEqual(
            chan.getElementsByTagName('atom:link')[0].getAttribute('href'),
            'http://example.com/syndication/rss2/'
        )

        # Find the pubdate of the first feed item
        d = Entry.objects.get(pk=1).date
        ltz = tzinfo.LocalTimezone(d)
        pub_date = rfc2822_date(d.replace(tzinfo=ltz))

        items = chan.getElementsByTagName('item')
        self.assertEqual(len(items), Entry.objects.count())
        self.assertChildNodeContent(items[0], {
            'title': 'My first entry',
            'description': 'Overridden description: My first entry',
            'link': 'http://example.com/blog/1/',
            'guid': 'http://example.com/blog/1/',
            'pubDate': pub_date,
            'author': 'test@example.com (Sally Smith)',
        })
        self.assertCategories(items[0], ['python', 'testing'])

        for item in items:
            self.assertChildNodes(item, ['title', 'link', 'description', 'guid', 'category', 'pubDate', 'author'])

    def test_rss091_feed(self):
        """
        Test the structure and content of feeds generated by RssUserland091Feed.
        """