###
# API Call
###

from datetime import datetime
import pydelicious
from time import strptime

from YOURPROJECT.blog.decorators import cache_function
from YOURPROJECT.blog.models import Bookmark
from YOURPROJECT import settings

@cache_function(60*10)
def delicious():
    """Call the del.icio.us API, and cache the call for ten (10) minutes."""
    api = pydelicious.apiNew(settings.DELICIOUS_USER, settings.DELICIOUS_PASS)
    recent_posts = api.posts_recent(count='5') # Count must be a string
    
    for post in recent_posts:
        # Check if the post already exists, based on the hash
        post['dt'] = datetime(*strptime(post['dt'], '%Y-%m-%dT%H:%M:%SZ')[0:6])
        post_hash = post['hash']
        
        valid_params = ['description', 'extended', 'href', 'dt', 'tags']
        post = dict([(k,v) for k,v in post.items() if k in valid_params])
        
        post_object = Bookmark.objects.get_or_create(address_hash=post_hash,
            defaults=post)
        
        if not post_object[1]: # If it wasn't just created
            for param in valid_params:
                if post_object[0].__getattribute__(param) != post[param]:
                    post_object[0].__setattr__(param, post[param])
            post_object[0].save()

###
# Bookmarks model
###

class Bookmark(models.Model):
    """
    A del.icio.us bookmark. This will be automatically created based on
    calls to the del.icio.us API.
    """
    address_hash = models.CharField(blank=False, maxlength=32)
    description = models.CharField(blank=False, maxlength=255)
    extended = models.TextField(blank=True)
    href = models.URLField()
    dt = models.DateTimeField()
    
    tags = models.CharField(maxlength=250, validator_list=[isTagList],
        help_text='Seperate tags with spaces.')
    
    class Admin:
        pass
    
    def title(self):
        "Mimics the title field in other models."
        return self.description
    
    def __str__(self):
        return self.title()
    
    def save(self):
        super(Bookmark, self).save()
        Tag.objects.update_tags(self, self.tags)