"""$URL$
$Id$
"""

from urlparse import urlsplit, urlunsplit
from mx import DateTime
from dulcinea.item import Item, ItemFolder
from dulcinea.base import DulcineaPersistent
from dulcinea.spec import any
from dulcinea.typeutils import typecheck

class LinkItem(Item):
    """
    Instance attributes:
       split_url : [ string ]
          urlsplited URL to redirect to
    """

    split_url_is = any([ str ], None)

    def __init__(self, timestamp=None):
        Item.__init__(self, timestamp=timestamp)
        self.split_url = None

    def set_url(self, url):
        typecheck(url, str)
        split_url = urlsplit(url)
        assert split_url[0] in ('ftp', 'http', 'https'), (
            "unknown URL scheme '%s'" % split_url[0])
        self.split_url = split_url
        self.timestamp = DateTime.now()

    def get_url(self):
        return urlunsplit(self.split_url)


LinkFolder = ItemFolder

def sort_reverse_by_date(link1, link2):
    # Sort links cronologically with most recent first
    return cmp(link2.get_timestamp(), link1.get_timestamp())

