from yafowil.base import factory
from yafowil.controller import Controller
from paste.httpexceptions import HTTPFound
from bda.bfg.tile import Tile
from bda.bfg.app.browser.utils import make_url

class Form(Tile):
    
    @property
    def form(self):
        """Return yafowil compound.
        
        Not implemented in base class.
        """
        raise NotImplementedError(u"``form`` property must be provided "
                                  u"by deriving object.")
    
    def __call__(self, model, request):
        self.model = model
        self.request = request
        return self._process_form(self.form)
    
    def _process_form(self, form):
        self.prepare()
        if not self.show:
            return ''
        controller = Controller(form, self.request)
        if not controller.next:
            return controller.rendered
        if isinstance(controller.next, HTTPFound):
            self.redirect(controller.next.location())
            return
        return controller.next
        
class AddForm(Form):
    """form hooking the hidden value 'factory' to self.form on __call__
    """
    
    def __call__(self, model, request):
        self.model = model
        self.request = request
        form = self.form
        form['factory'] = factory('proxy', value=request.params.get('factory'))
        return self._process_form(form)
    
    def next(self, request):
        return HTTPFound(make_url(request.request, node=self.model.__parent__))

class EditForm(Form):
    """form hooking the hidden value 'from' to self.form on __call__
    """
    
    def __call__(self, model, request):
        self.model = model
        self.request = request
        form = self.form
        form['from'] = factory('proxy', value=request.params.get('from'))
        return self._process_form(form)
    
    def next(self, request):
        if request.get('from') == 'parent':
            url = make_url(request.request, node=self.model.__parent__)
        else:
            url = make_url(request.request, node=self.model)
        return HTTPFound(url)
@@ -610,25 +610,16 @@
 ss_form(
-self.form
 )%0A    %0A 
@@ -649,16 +649,21 @@
 lf, form
+=None
 ):%0A     
@@ -680,16 +680,49 @@
 epare()%0A
+        form = form or self.form%0A
         

call Form.prepare() before accessing the Form.form property