# Copyright (c) 2004 Infrae. All rights reserved.
# See also LICENSE.txt
# python
import urlparse
# Zope
from OFS import SimpleItem
from Globals import InitializeClass
from AccessControl import ClassSecurityInfo, Permissions
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
# Railroad
from Products.Railroad import interfaces, errors, proxy, utils

class RailroadProxy(proxy.Proxy, SimpleItem.SimpleItem):
    """Zope wrapper proxy object
    """
    
    meta_type = "Railroad Proxy"
    
    security = ClassSecurityInfo()

    manage_options = (
        {'label':'Edit', 'action':'manage_railroadProxyEditForm'},
        {'label':'Upload', 'action':'manage_railroadUploadResourceForm'},
        {'label':'Properties', 'action':'manage_railroadProxyPropertiesForm'},
        ) + SimpleItem.SimpleItem.manage_options

    management_page_charset = 'utf-8'
    
    def __init__(self, id, title, unique_id):
        self.id = id
        self.title = title
        proxy.Proxy.__init__(self, unique_id)

    security.declareProtected(
        'View management screens', 'manage_railroadProxyEdit')
    def manage_railroadProxyEdit(
        self, title, resource_path, service_id, REQUEST=None):
        """Edit basic Zope Railroad Proxy object
        """
        
        msg = ['Settings changed.',]
        
        if title:
            self.title = title

        if resource_path:
            stripped = False
            while resource_path.startswith('/'):
                resource_path = resource_path[1:]
                stripped = True
            if stripped:
                msg.append('Leading slash stripped from resource path.')
            self.set_resource_path(resource_path)
            
        if service_id:
            # Get the service via acquisition for now
            # XXX we need some sort of registry here I guess
            service = getattr(self, service_id, None)
            if service is None or \
                    not interfaces.IRailroadService.isImplementedBy(service):
                msg.append(
                    'No Railroad service with id "%s" can be found.' % service_id)
            else:
                self.set_railroad_service(service)
            
        msg = ' '.join(msg)
        if REQUEST is not None:
            return self.manage_railroadProxyEditForm(manage_tabs_message=msg)
        return msg

    security.declareProtected(
        'View management screens', 'manage_railroadProxyProperties')
    def manage_railroadProxyProperties(self, properties_dict):
        """Edit properties for basic Zope Railroad Proxy object
        """
        pass

    security.declareProtected(
        'View management screens', 'manage_railroadProxyEditForm')
    manage_railroadProxyEditForm = PageTemplateFile(
        'www/railroadProxyEdit', globals(),  
        __name__='manage_railroadProxyEditForm')

    security.declareProtected(
        'View management screens', 'manage_railroadUploadResourceForm')
    manage_railroadUploadResourceForm = PageTemplateFile(
        'www/railroadUploadResource', globals(),  
        __name__='manage_railroadUploadResourceForm')

    security.declareProtected(
        'View management screens', 'manage_railroadProxyPropertiesForm')
    manage_railroadProxyPropertiesForm = PageTemplateFile(
        'www/railroadProxyProperties', globals(),  
        __name__='manage_railroadProxyPropertiesForm')
        
    security.declareProtected('View management screens', 'manage_main')
    manage_main = manage_railroadProxyEditForm
    
    def index_html(self):
        """ Redirect to resource URL if available
        """
        if not self.has_resource():
            return (
                'Proxy "%s" does not have a resource assigned') % self.title_or_id()
        request = self.REQUEST
        response = request.RESPONSE
        url = self.resource_url()
        return response.redirect(url)
    
    # RAILROAD EVENTS
    
    security.declareProtected('View', 'on_upload_succeeded')
    def on_upload_succeeded(self, url, errormsg):
        """Notifies proxy of a succesful resource upload to the Railroad
        repository.
        
        Method should be publishable (i.e., the implementation needs
        to have a doc string).
        """
        proxy.Proxy.on_upload_succeeded(self, url, errormsg)
        request = self.REQUEST
        redirect_url = self.absolute_url() + '/manage_main'
        request.RESPONSE.redirect(redirect_url)
    
    security.declareProtected('View', 'on_upload_failed')
    def on_upload_failed(self, errormsg):
        """Notifies proxy of a failed resource upload to the Railroad
        repository.
        
        Method should be publishable (i.e., the implementation needs
        to have a doc string).
        """
        proxy.Proxy.on_upload_failed(self, url, errormsg)
        raise errors.RailroadError(errormsg + ' ' + url)

    # ZOPE EVENTS
    
    security.declareProtected(
        'View management screens', 'manage_afterAdd')
    def manage_afterAdd(self, item, container):
        self.on_create()
    
    security.declareProtected(
        'View management screens', 'manage_afterClone')
    def manage_afterClone(self, item): 
        self.on_paste()
            
    security.declareProtected(
        'View management screens', 'manage_beforeDelete')
    def manage_beforeDelete(self, item, container):
        self.on_delete()

InitializeClass(RailroadProxy)

manage_addRailroadProxyForm = PageTemplateFile(
    "www/railroadProxyAdd", globals(), __name__='manage_addRailroadProxyForm')

def manage_addRailroadProxy(context, id, title, unique_id, REQUEST=None):
    """Add basic Zope Railroad Proxy object
    """
    proxy = RailroadProxy(id, title, unique_id)
    context._setObject(id, proxy)
    proxy = getattr(context, id)
    utils.add_and_edit(context, id, REQUEST)
    return proxy
    