from pecan.core import Pecan as PecanApplication
from pecan_mount._compat import native_to_unicode, py3k
from pecan_mount.util import downgrade_wsgi_ux_to_1x, urljoin


class Tree(object):
    """
    A registry of Pecan applications, mounted at diverse points.

    An instance of this class may also be used as a WSGI callable
    (WSGI application object), in which case it dispatches to all
    mounted apps.

    .. attribute:: apps
    A dict of the form {script name: application}, where "script name" is
    a string declaring the URI mount point (no trailing slash), and
    "application" is an instance of pecan.Application (or an arbitrary WSGI
    callable if you happen to be using a WSGI server).
    """

    def __init__(self):
        self.apps = {}

    def app_name(self, script_name):
        """
        Return the name of the app mounted for a given script_name
        or None.
        """
        if script_name in self.apps:
            return self.apps[script_name].__class__.__name__
        return None

    def mount(self, script_name="", config=None):
        """Mount a new app from a root object, script_name, and config.

        script_name
            A string containing the "mount point" of the application.
            This should start with a slash, and be the path portion of the
            URL at which to mount the given root. For example, if root.index()
            will handle requests to "http://www.example.com:8080/dept/app1/",
            then the script_name argument would be "/dept/app1".

            It MUST NOT end in a slash. If the script_name refers to the
            root of the URI, it MUST be an empty string (not "/").

        config
            A file or dict containing application config.
        """
        # Prevent a None value *always*
        script_name = script_name or ""

        # Prevent stepping over something already mounted
        if script_name in self.apps:
            raise AttributeError(
                "The script_name <'%s'> is already mounted for app "
                "<%s>" % (script_name, self.app_name(script_name)))

        # Next line both 1) strips trailing slash and 2) maps "/" -> "".
        script_name = script_name.rstrip("/")

        from pecan.core import load_app
        app = load_app(config)
        app.script_name = script_name

        # FIXME: we need to try and merge the config here
        #if config:
            #app.merge(config)

        self.apps[script_name] = app

        return app

    def graft(self, wsgi_callable, script_name=""):
        """Mount a wsgi callable at the given script_name."""
        # Next line both 1) strips trailing slash and 2) maps "/" -> "".
        script_name = script_name.rstrip("/")
        self.apps[script_name] = wsgi_callable

    def script_name(self, path):
        """
        The script_name of the app at the given path, or None.
        """
        while True:
            if path in self.apps:
                return path

            if path == "":
                return None

            # Move one node up the tree and try again.
            path = path[:path.rfind("/")]

    def __call__(self, environ, start_response):
        # Try to look up the app using the full path.
        env1x = environ
        if environ.get(native_to_unicode('wsgi.version')) == (native_to_unicode('u'), 0):
            env1x = downgrade_wsgi_ux_to_1x(environ)
        path = urljoin(env1x.get('SCRIPT_NAME', ''),
                       env1x.get('PATH_INFO', ''))
        sn = self.script_name(path or "/")
        if sn is None:
            start_response('404 Not Found', [])
            return []

        app = self.apps[sn]

        # Correct the SCRIPT_NAME and PATH_INFO environ entries.
        # Note that we are not modifying SCRIPT_NAME until Pecan issue #175
        # gets fixed
        # Ideally, we would update the SCRIPT_NAME here with the proper
        # value from the app that was mounted
        environ = environ.copy()
        if not py3k:
            if environ.get(native_to_unicode('wsgi.version')) == (native_to_unicode('u'), 0):
                # Python 2/WSGI u.0: all strings MUST be of type unicode
                enc = environ[native_to_unicode('wsgi.url_encoding')]
#                environ[native_to_unicode('SCRIPT_NAME')] = sn.decode(enc)
                environ[native_to_unicode('PATH_INFO')] = path[len(sn.rstrip("/")):].decode(enc)
            else:
                # Python 2/WSGI 1.x: all strings MUST be of type str
#                environ['SCRIPT_NAME'] = sn
                environ['PATH_INFO'] = path[len(sn.rstrip("/")):]
        else:
            if environ.get(native_to_unicode('wsgi.version')) == (native_to_unicode('u'), 0):
                # Python 3/WSGI u.0: all strings MUST be full unicode
#                environ['SCRIPT_NAME'] = sn
                environ['PATH_INFO'] = path[len(sn.rstrip("/")):]
            else:
                # Python 3/WSGI 1.x: all strings MUST be ISO-8859-1 str
#                environ['SCRIPT_NAME'] = sn.encode('utf-8').decode('ISO-8859-1')
                environ['PATH_INFO'] = path[len(sn.rstrip("/")):].encode('utf-8').decode('ISO-8859-1')

        return app(environ, start_response)



@@ -5239,8 +5239,311 @@
 onse)%0A%0A%0A
+#%0A# Helpers%0A#%0Adef name_from_path(path):%0A    %22%22%22%0A    Given a path, try to determine the name for it, replacing%0A    slashes for dots.%0A    Alternatively, just return 'root' if nothing is passed to%0A    this helper.%0A    %22%22%22%0A    if not path:%0A        return 'root'%0A    return path.strip('/').replace('/', '.')%0A

create a helper for inferring app names