import sys
import logging

class BaseWSGIApplication(object):
    def postInitialize(self,controller, kargs):
        pass

    def initializeCommandFactory(self, request, response, environ, session, mapperPath):
        # Match the path against registered routes.
        method = request.params.get('__method')
        if method:
            environ['REQUEST_METHOD'] = method
        mimetype = request.params.get('mimetype')
        if mimetype:
            request.accept = mimetype

        self.mapper._envset(environ)
        controller = None

        self.mapper._envset(environ)
        if request.path=='/favicon.ico':
            return
        kargs = self.mapper.match(mapperPath)
        if kargs is None:
            raise TypeError('No routes match for %s.The method is %s. Provide a fallback to avoid this.'%(mapperPath, environ['REQUEST_METHOD']))
        # Extract the module and controller names from the route.
        try:
            module_name, class_name = kargs['controller'].split(':', 1)
            del kargs['controller']
        except Exception ,e:
            logging.error(str(e))
            raise #TypeError('Controller is not set, or not formatted in the form "my.module.name:MyControllerName".')

        # Initialize matched controller from given module.
        try:
            __import__(module_name)
            module = sys.modules[module_name]
#            logging.info(str(module))
            controller = getattr(module, class_name)()
            controller.initialize(request, response)
            controller.setSession(session)
            #update the app configuration based on Global Instance values
#            from orangescape.model.server.util.ServerUtil import updateGlobalParameters
#            from orangescape.model.server.Context import getGlobalInstance
#            updateGlobalParameters(getGlobalInstance(session))

            self.postInitialize(controller, kargs)
        except Exception ,e:
            logging.error(str(e))
            raise #ImportError('Controller %s from module %s could not be initialized.' % (class_name, module_name))

        # Use the action set in the route, or the HTTP method.
        if 'action' in kargs:
            action = kargs['action']
            del kargs['action']
        else:
            action = environ['REQUEST_METHOD'].lower()
            if action not in ['get', 'post', 'head', 'options', 'put', 'delete', 'trace']:
                action = None

        return controller,action,kargs