#!ipy

"""
+++++++++++
 router.py
+++++++++++

 author: Jesse Wiles
 copyright: Quadralay Corporation
 
 Class for reading a resources file.  Helper static method provided for
 reading a web URI into a string.
"""

from System import Uri
from System.IO import StreamReader
from System.Net import WebRequest, CredentialCache

import clr
clr.AddReference('System.Xml')
from System.Xml import XmlReader
from System.Xml.XPath import XPathDocument

class Router(object):
    _content_type = None

    def __init__(self, env):
        self._reader = XmlReader.Create(env.source)

        _xpdoc = XPathDocument(self._reader)
        _nav = _xpdoc.CreateNavigator()
        _node = _nav.SelectSingleNode("//node()[local-name() = 'resource'][1]")

        self._nodenav = _node.CreateNavigator()

        env['uri'] = self.uri

        content_types = {
            'text/x-rst': 'rst', 
            'application/docbook+xml': 'docbook'
        }
        
        if content_types.has_key(self.content_type):
            self._content_type = content_types[self.content_type]

        self._reader.Close()

        if self._content_type is not None:
            mod_name = self._content_type
            cls_name = '%s%s' % (mod_name[0:1].upper(), mod_name[1:])
            mod = __import__(mod_name, globals(), locals(), [cls_name])

            # Instantiate endpoint class with env and call method
            #
            ep = getattr(mod, cls_name)(env)
            call = getattr(ep, env.method)
            call()
            
        else:
            raise

    @property
    def content_type(self):
        return self._nodenav.SelectSingleNode("./@content-type").ToString()
    
    @property
    def uri(self):
        return Uri(self._nodenav.SelectSingleNode("./@id").ToString())
