# Copyright (c) 2002-2009 Infrae. All rights reserved.
# See also LICENSE.txt
# Zope 3
import zope.component
from zope.interface import implements
from zope.traversing.browser.interfaces import IAbsoluteURL
# Five
from OFS.interfaces import ITraversable
from Products.Five import BrowserView
# SilvaLayout
from Products.SilvaLayout.interfaces import ITreeNode
from Products.Silva.interfaces import IContent

class AbsoluteURL(BrowserView):
    """An adapter for Zope3-style absolute_url using Zope2 methods

    (original: zope.traversing.browser.absoluteurl)
    """

    implements(IAbsoluteURL)
    
    def __init__(self, context, request):
        self.context = context
        self.request = request

    def __str__(self):
        return self.context.absolute_url()

    __call__ = __repr__ = __str__

    def breadcrumbs(self):
        context = self.context.aq_inner
        container = context.aq_parent
        request = self.request

        name = context.get_short_title()
        if len(name) > 50:
            name = name[:47] + '...'
        
        if (container is None or self._isVirtualHostRoot() or 
                not ITraversable.providedBy(container)):
            return (
                {'name': name, 'url': context.absolute_url()},)

        id = context.id
        base = tuple(zope.component.getMultiAdapter(
                     (container, request), name='absolute_url').breadcrumbs())

        if not (IContent.providedBy(self.context) and self.context.is_default()):
            base += (
                {'name': name, 'url': ("%s/%s" % (base[-1]['url'], id))},)
        return base

    def _isVirtualHostRoot(self):
        treenode = ITreeNode(self.context)
        vhroot = treenode.getVirtualHostRootNode()
        return vhroot.context == self.context

class SiteAbsoluteURL(AbsoluteURL):
    """An adapter for Zope3-style absolute_url using Zope2 methods

    This one is just used to stop breadcrumbs from crumbing up
    to the Zope root.

    (original: zope.traversing.browser.absoluteurl)
    """

    implements(IAbsoluteURL)

    def breadcrumbs(self):
        context = self.context
        request = self.request
        name = context.get_short_title()
        if len(name) > 50:
            name = name[:47] + '...'
            
        return ({'name': name,
                 'url': context.absolute_url()
                 },)
