# Example #3: Pointless Portal
#  by Leonard Richardson (leonardr@segfault.org)
#   Base CGI class for portal.cgi, preferences.cgi, and configure.cgi

import os
import cgi
import string
import types

import IWantOptions
from BusinessObjects import User, Site, SimpleOptionWrapper

class CGI:

    def __init__(self):
        self.getVariables()

        wrapper = SimpleOptionWrapper()

        user = self.variables.get('user', None)
        if not user:
            user = 'guest'
        userOptions = self.getDefinitionFile('userOptions')
        self.config = IWantOptions.OptionConfig(userOptions, wrapper)
        self.user = User(self.config, self.getDataDir('user'),
                         user)
        
        siteOptions = self.getDefinitionFile('siteOptions')
        self.siteConfig = IWantOptions.OptionConfig(siteOptions, wrapper)
        self.site = Site(self.siteConfig, os.path.join(self.getDataDir('site'),
                                                       'options'))

        self.run()

    def getVariables(self):
        self.variables = {}
        form = cgi.FieldStorage()
        if form.list:
            for key in form.keys():            
                if type(form[key]) == types.ListType:
                    #This is to handle one CGI field with multiple
                    #values. We want a list of the string values
                    #rather than a list of MiniFieldStorage objects.
                    value = []
                    for field in form[key]:
                        value.append(field.value)
                else:
                    value = form[key].value
                self.variables[key] = value

    def getDefinitionFile(self, file):
        "Returns the path to a file in the definition directory."
        return os.path.join(os.getcwd(), 'definitionStore', file)

    def getDataDir(self, type):
        "Returns the path to a subdirectory of the data directory."
        return os.path.join(self.getBaseDataDir(), type)

    def getBaseDataDir(self):
        return 'data/'

    def personalize(self, s):
        """Personalizes a string by replacing %R and %U with the user's
        real name and login name."""
        realName = self.user.getRealName()
        s = string.replace(s, "%R", realName)
        username = self.user.getUsername()
        s = string.replace(s, "%U", username)
        return s            

    def __getitem__(self, key):
        "Returns a value from the configuration."
        return self.config.getOptionValue(key, self.context)

    def run(self):
        "Hook method."
        pass

class ConfigurationCGI(IWantOptions.ConfigurationCGI, CGI):

    def __init__(self, config, context, formURL, title):
        CGI.__init__(self)
        IWantOptions.ConfigurationCGI.__init__(self, getattr(self, config),
                                               getattr(self, context),
                                               formURL + '?user=' + self.user.getUsername(),
                                               title)

    def startForm(self):
        IWantOptions.ConfigurationCGI.startForm(self)
        print '<input type="hidden" name="user" value="%s">' % self.user.getUsername()

    def endPage(self):
        print '<hr><a href="portal.cgi?user=%s">Back to the portal</a>' % self.user.getUsername()
        IWantOptions.ConfigurationCGI.endPage(self)


