# Copyright (c) 2002-2007 Infrae. All rights reserved.
# See also LICENSE.txt
# $Revision: 1.25 $

from zope.interface import implements

import os

from Globals import InitializeClass, package_home
from AccessControl import ClassSecurityInfo
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
from zExceptions import NotFound

from Products.SilvaExternalSources.interfaces import IExternalSource
from Products.SilvaExternalSources.CodeSource import CodeSource

from Products.Silva import SilvaPermissions
from Products.Silva.helpers import add_and_edit

from OFS.Image import Image

from Products.Formulator.Form import ZMIForm
from Products.Formulator.XMLToForm import XMLToForm

def ustr(x):
    if type(x) == unicode:
        return x
    elif type(x) == str:
        return unicode(x, 'UTF-8')
    return str(x)

class MailingSubscriptionForm(CodeSource):
    """ provides an subscription and unsubscription form for mailings
    """
    implements(IExternalSource)
    meta_type = 'Silva Mailing Subscription Form'
    security = ClassSecurityInfo()

    def __init__(self, id, path=''):
        MailingSubscriptionForm.inheritedAttribute('__init__')(self, id)
        self._script_id = 'view'
        self._data_encoding = 'UTF-8'
        self.refresh()

    # XXX added this as a seperate, ttw accessible method to easily allow
    # refreshing the code source's contents while testing...
    security.declareProtected(SilvaPermissions.ChangeSilvaAccess,
                              'refresh')
    def refresh(self):
        """reload the form and pt"""
        if 'view' in self.objectIds():
            self.manage_delObjects(['view'])
        # XXX this code doesn't look like it can work,
        # as rrs10.gif is not removed and set_views tries to
        # add it again
        self._set_form()
        self._set_views()

    def _set_form(self):
        self.parameters = ZMIForm('form', 'Properties Form')
        fp = open(os.path.join(
                  package_home(globals()), 
                  'www', 
                  'subscription_form_parameters.form'))
        try:
            xml = fp.read()
        finally:
            fp.close()
        XMLToForm(xml, self.parameters)
        fp.close()

    def _set_views(self):
        fp = open(os.path.join(
                  package_home(globals()),
                  'www',
                  'subscription_form_view.pt'))
        try:
            data = fp.read()
        finally:
            fp.close()
        self._setObject('view', ZopePageTemplate('view', data))

        self.subscription_form = sf = ZMIForm('subscription_form',
                                              'Subscription Form')
        fp = open(os.path.join(
                  package_home(globals()), 
                  'www',
                  'subscription_form.form'))
        try:
            xml = fp.read()
        finally:
            fp.close()
        XMLToForm(xml, self.subscription_form)

    security.declareProtected(SilvaPermissions.AccessContentsInformation,
                                'to_html')
    def to_html(self, *args, **kwargs):
        """render the news list"""
        # XXX this is screwed up, both because the name clashes with the
        # 'normal' request.model, and because this leaks memory (have to
        # store stuff in request.other instead)
        self.REQUEST.form['model'] = self
        try:
            return ustr(getattr(self, 'view')(**kwargs))
        except:
            import sys, traceback
            exc, e, tb = sys.exc_info()
            tbs = '\n'.join(traceback.format_tb(tb))
            del tb
            ret =  '%s - %s<br />\n\n%s<br />' % (exc, e, tbs)
            return ret

InitializeClass(MailingSubscriptionForm)

manage_addMailingSubscriptionFormForm = PageTemplateFile(
    "www/subscription_form_add", globals(),
    __name__='manage_addMailingSubscriptionFormForm')

def manage_addMailingSubscriptionForm(context, id, title, REQUEST=None):
    """Add an Mailing Subscription Form"""
    v = MailingSubscriptionForm(id)
    context._setObject(id, v)
    add_and_edit(context, id, REQUEST)
    v = getattr(context, id)
    v.title = unicode(title, 'UTF-8')
    return ''

