#
# Copyright 2001 by Object Craft P/L, Melbourne, Australia.
#
# LICENCE - see LICENCE file distributed with this software for details.
#
import cgi
import sys
import os


class FileField:

    def __init__(self, field):
        self.filename = field.filename
        self.file = field.file
        self.type = field.type

    def __repr__(self):
        return 'FileField(%s, %s, %s)' % (self.filename, self.file, self.type)


class RequestFields:

    def __init__(self, fields):
        self.__fields = fields

    def has_field(self, name):
        return self.__fields.has_key(name)

    def field_value(self, name):
        field = self.__fields[name]
        if isinstance(field, type([])):
            if isinstance(field[0], type('')):
                # For checkboxes, this is a vec of strings in mod_python 2
                return field
            # But a vec of utils.FieldStorage objects in mod_python 3
            return [f.value for f in field]
        elif isinstance(field, type('')):
            return field                # Weird - blame mod_apache?
        else:
            return field.value

    def field_file(self, name):
        field = self.__fields[name]
        if isinstance(field, type([])):
            return [FileField(f) for f in field]
        if field.type.startswith('multipart'):
            return [FileField(f) for f in field.value]
        else:
            return [FileField(field)]

    def field_names(self):
        return self.__fields.keys()


class Request(RequestFields):

    def __init__(self, fields = None):
        if fields is None:
            fields = cgi.FieldStorage()
        RequestFields.__init__(self, fields)
        self.__status = 200

    def get_uri(self):
        return os.environ.get('REQUEST_URI')

    def get_path_info(self):
        return self.__fcgi.env.get('PATH_INFO')

    def get_servername(self):
        return os.environ.get('HTTP_HOST')

    def get_header(self, name):
        env_name = 'HTTP_' + name.upper().replace('-', '_')
        return os.environ.get(env_name)

    def write_header(self, name, value):
        sys.stdout.write('%s: %s\n' % (name, value))

    def end_headers(self):
        sys.stdout.write('\n')

    def redirect(self, loc):
        self.write_header('Location', loc)
        self.write_header('Status', '301 Moved Permanently')
        self.end_headers()

    def write_content(self, data):
        sys.stdout.write(data)
        sys.stdout.flush()

    def set_status(self, status):
        self.__status = status

    def status(self):
        return self.__status
