import datetime

from django.db import models
from django.contrib.auth.models import User
from django.conf import settings

from hadrian.utils.slugs import unique_slugify

import feedparser

from .managers import FeedItemManager


class Category(models.Model):
    name = models.CharField(max_length=250, blank=True)
    slug = models.SlugField(blank=True, null=True, editable=False)
    user = models.ForeignKey(User, blank=True, null=True)

    def __unicode__(self):
        return self.name

    def save(self, *args, **kwargs):
        unique_slugify(self, self.name)
        super(Category, self).save(*args, **kwargs)

    @property
    def get_unread_count(self):
        return FeedItem.objects.my_feed_items(self.user).category(self.slug).un_read().count()


class Feed(models.Model):
    url = models.CharField(blank=True, max_length=450, unique=True)
    title = models.CharField(blank=True, null=True, max_length=250)
    category = models.ForeignKey(Category, blank=True, null=True)
    user = models.ForeignKey(User, blank=True, null=True)
    last_update = models.DateField(blank=True, null=True, editable=False)

    def __unicode__(self):
        return self.url

    def _get_title(self):
        parser = feedparser.parse(self.url)
        return parser.feed.title

    def save(self, *args, **kwargs):
        if not self.title:
            self.title = self._get_title()
        super(Feed, self).save(*args, **kwargs)
        if self.last_update is None:
            self.update(force=True)

    @property
    def get_unread_count(self):
        return FeedItem.objects.filter(feed=self).un_read().count()

    def _update_feed(self):
        # Update the last update field
        self.last_update = datetime.date.today()
        self.save()
        for item in feedparser.parse(self.url).entries[:10]:
            # Search for an existing item
            try:
                FeedItem.objects.get(title=item.title)
            except FeedItem.DoesNotExist:
                # Create it.
                feed_item = FeedItem(title=item.title, link=item.link, content=item.description, feed=self)
                feed_item.save()

    def _update_processor(self):
        if getattr(settings, 'FEED_UPDATE_CELERY', False):
            from .tasks import update_feed
            update_feed.delay(self)
            return True
        self._update_feed()
        return True

    def update(self, force=False):
        """ If we aren't forcing it
        and its not the same day, go ahead
        and update the feeds.
        """

        if force or not force and self.last_update < datetime.date.today():
            self._update_processor()
            return True

    @models.permalink
    def get_absolute_url(self):
        return ('feedme-feed-list-by-feed', (), {'feed_id': self.id})


class FeedItem(models.Model):
    title = models.CharField(max_length=350, blank=True)
    link = models.URLField(blank=True)
    content = models.TextField(blank=True)
    feed = models.ForeignKey(Feed, blank=True, null=True)
    read = models.BooleanField()

    objects = FeedItemManager()

    class Meta:
        ordering = ['id']

    def __unicode__(self):
        return self.title


@@ -10,16 +10,41 @@
 tetime%0A%0A
+from time import mktime%0A%0A
 from dja
@@ -809,24 +809,164 @@
 els.Model):%0A
+    class Meta:%0A        unique_together = (%0A            (%22url%22, %22user%22),%0A        )%0A%0A    link = models.CharField(blank=True, max_length=450)%0A
     url = mo
@@ -1010,21 +1010,8 @@
 =450
-, unique=True
 )%0A  
@@ -1072,24 +1072,25 @@
 length=250)%0A
+%0A
     category
@@ -2031,12 +2031,197 @@
     
-try:
+if item.has_key(%22id%22):%0A                guid = item.id%0A            else:%0A                guid = item.link%0A            try:%0A                # FIXME(halldor): this should use the feed item UID
 %0A   
@@ -2254,32 +2254,25 @@
 cts.get(
-title=item.title
+guid=guid
 )%0A      
@@ -2336,16 +2336,386 @@
 ate it.%0A
+                if item.has_key(%22published_parsed%22):%0A                    pub_date = datetime.datetime.fromtimestamp(mktime(item.published_parsed))%0A                elif item.has_key(%22updated_parsed%22):%0A                    pub_date = datetime.datetime.fromtimestamp(mktime(item.updated_parsed))%0A                else:%0A                    pub_date = datetime.datetime.now()%0A%0A
         
@@ -2802,16 +2802,83 @@
 ription,
+%0A                                     guid=guid, pub_date=pub_date,
  feed=se
@@ -3839,16 +3839,98 @@
 nField()
+%0A    guid = models.CharField(max_length=255)%0A    pub_date = models.DateTimeField()
 %0A%0A    ob

Update the unique constraint on the Feed object. Also add Feed.link (the url of the web page), FeedItem.guid (unique id) and FeedItem.pub_date (when the item was initially published).