import string
import time

import libxml2 #;libxml2.debugMemory(1)
import libxslt

import jon.cgi as cgi
import jon.modpy as modpy

import Handler
from Handler import PATH_XML_DOCS
from Handler import PATH_XSL_DOCS
from Handler import PATH_ASI_PROC
from Handler import REFRESH_MESSAGE

AUTO_PID = '0'
DROP_PID = '1FFF'

def debug(req, msg):
    DEBUG = 0
    if DEBUG:
        req.error(msg)

class AdvMappingsHandler(Handler.Handler):

    _adminPage = 'mappings.xsl'
    _roPage = 'romappings.xsl'

    def htmlHeaders(self, req):
        req.set_header('Content-Type', 'text/html')

    def htmlDoctype(self, req):
        req.write('<?xml version="1.0"?>')
        req.write('\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n')
    
    def htmlHead(self, req, title='', refresh=8, href='advmappings.py'):
        req.write('<head><title>%s</title><meta http-equiv="Refresh" content="%d;URL=%s" /></head>' % (title, refresh, href))
        
    def htmlString(self, req, msg):
        req.write(msg)

    #def htmlComment(self, req, msg):
    #    req.write('\n<!-- %s -->' % (msg,))
        
    def xpathRemove(self, path):
        nodeset = self._muxconfig.xpathEval2(path)
        if len(nodeset) == 1:
            nodeset[0].unlinkNode()
            nodeset[0].freeNode()
   
    def handleMultiParams(self, req, key):
        nvDict = {}
        #xpath = key[6:-1]
        temp = key[6:-1].split('?')
        xpath = temp[0]
        if len(temp) == 2:
            args = temp[1].split('^')
            for nvstr in args:
                nv = nvstr.split('=')
                nvDict[nv[0]] = nv[1]
        if 'pid_out' in xpath:
            if req.params[key][0] == '0000' or req.params[key][0] == '1FFF':
                val = req.params[key][0]
            else:
                val = req.params[key][1]
            #val = req.params[key][1]
        elif xpath[-21:] == 'stream_dest_inet_addr':
            # validate???
            if ((len(req.params[key]) == 4)
                    and (req.params[key][0] != '')
                    and (req.params[key][1] != '')
                    and (req.params[key][2] != '')
                    and (req.params[key][3] != '')):
                val = string.join(req.params[key], '.')
            else:
                val = ''
        elif (xpath[-16:] == '@access_criteria' 
                or xpath[-6:] == '@index'
                or xpath[-23:] == '@access_criteria_length'
                or xpath[-20:] == '@private_data_length'
                or xpath[-13:] == '@private_data'
                or xpath[-18:] == '@ecm_pid_requested'):
            # validate???
            val = req.params[key][0]
        return (xpath, val, nvDict)

    def apply(self, req):
#        self.htmlHeaders(req)
#        self.htmlDoctype(req)
#        self.htmlString(req, '<html>')
#        self.htmlHead(req)
#        self.htmlString(req, '<body background="../../images/rightbackground.gif" text="White" link="White" vlink="White" alink="White">')
        try:
            debug(req, 'len params %d\n' % (len(req.params)))
            countXpath = 0
            for key in req.params:
                #debug(req, str(key)+'\n')
                #if (key.find('xpath:') == 0):
                if (key[0:6] == 'xpath:'):
                    #debug(req, key[-28:]+'\n')
                    countXpath += 1
                    xpath, val, kwargs = self.processParam(req, key)
                    self.xpathSet(req, xpath, val, **kwargs)
                    #if (key[-8:] == 'name_out'
                    #    #or key[-18:] == 'program_number_out'
                    #    or key[-12:] == 'provider_out'):
                    #    self.setParam(req, key)
                #if countXpath > 31:
                #    break
            debug(req, str(countXpath) +'\n')
            
            ret = self._muxconfig.saveFormatFile(PATH_XML_DOCS + self._configFile, 1)
            self._muxconfig.saveFormatFile(PATH_XML_DOCS + 'webref.xml', 1)
            self._message = REFRESH_MESSAGE
            self.view(req)
#            self._delay_href = 'advmappings.py'
        finally:
            pass
#            status.freeDoc()
#        self.htmlString(req, '\n<table width="100%%" cellspacing="0" cellpadding="0">')
#        self.htmlString(req, '\n<tr>')
#        self.htmlString(req, '\n<td>&nbsp;</td>')
#        self.htmlString(req, '\n<td><br /><br /><br /><br />')
#        self.htmlString(req, '\n<b><center><font face="Arial" color="#C6DDD3"> </font><BR>')
#        self.htmlString(req, '\n<font face="Arial" color="White"><a href="%s">%s</a></font></center></b><br>' % (self._delay_href, self._message))
#        self.htmlString(req, '\n<!-- Successful Logout message')
#        self.htmlString(req, '\n<b><center><font face="Arial" color="White">You have successfully logged out ! <br /></font></center></b><br />')
#        self.htmlString(req, '\n-->')
#        self.htmlString(req, '\n<!--   No new session message')
#        self.htmlString(req, '\n<b><center><font face="Arial" color="White">A new session is unavailable ! <br /></font></center></b><br />')
#        self.htmlString(req, '\n-->')
#        self.htmlString(req, '\n<br /><br /><br /><br />')
#        self.htmlString(req, '\n</td>')
#        self.htmlString(req, '\n<td>&nbsp;</td>')
#        self.htmlString(req, '\n</tr>')
#        self.htmlString(req, '\n</table></body></html>')
        #self._delay = 6
        #self._delay_href = 'advmappings.py'
        #self._delay_message = 'Apply successful (Please wait %d seconds for refresh)' % self._delay
        #self.view(req)
        return


          
#cgi.CGIRequest(AdvMappingsHandler).process()
def handler(modpy_request):
    return modpy.Request(AdvMappingsHandler).process(modpy_request)
    
