## Script (Python) "tab_status_delete_versions"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=Revoke approval of approved content
##
from Products.Formulator.Errors import FormValidationError
from Products.SilvaMailing.i18n import translate as _
from zope.i18n import translate

view = context
request = context.REQUEST
model = request.model
folder = model.aq_inner
silvapermissions = view.get_silva_permissions()

form = model.tab_status_form_mailing()

try:
    result = form.validate_all(request)
except FormValidationError, e:
    message = view.render_form_errors(e)
    return view.tab_status(message_type='error',
                           message=message)

sendtestemail = result['testemail'] or False
testemailaddress = result['testemailaddress'] or None
if sendtestemail and not testemailaddress:
    message = _('please provide a test email address')
    return view.tab_status(message_type='error',
                           message=message)

try:
    folder.send_as_mailing('/'.join(model.getPhysicalPath()),
                           test_only=sendtestemail,
                           test_email=testemailaddress)
except AttributeError, e:
    message_type = 'error'
    message = _('missing ${missing_item}',
                mapping={'missing_item':e})

except Exception, e:
    # let's catch all here, don't know what the mailhost might raise...
    message_type = 'error'
    # XXX some nasty generics here...
    if not hasattr(e, 'message'):
        msg = str(e)
    else:
        msg = e.message
    if same_type(msg, {}):
        msg = ', '.join(['%s: %s' % (k, v) for (k, v) in msg.items()])
    elif same_type(msg, ()):
        msg = ' - '.join(msg)
    message = _('unknown error: ${error}',
                mapping={'error':msg})

else:
    message_type = 'feedback'
    message = _('mail delivered successfully')
    message = translate(message)

request.response.redirect('%s/edit/tab_status?message_type=%s&message=%s' % (
                          model.absolute_url(), message_type, translate(message)))

return ''

# XXX not sure why this fails for me... must be some strange interaction
# between the Five views and Silva, for some reason 'model' was
# wrong after the request (note that this was caused by 'send_as_mailing'
# rendering the document view, if that code was disabled tab_status returned
# okay, so I guess view() messes about with the request or sth...)
return view.tab_status(message_type=message_type,
                       message=message)

