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

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

import Handler
from Handler import PATH_XML_DOCS
from Handler import PATH_XSL_DOCS

def debugline(req, msg):
    req.error(msg)
    
class TablesHandler(Handler.Handler):
    """
    If new fields are added the the HTML form, just add an entry in 
    the _ApplyMap with the format - FieldName: (xpathStr, createBool), -
    """
    _adminPage = 'tables.xsl'
    _roPage = 'rotables.xsl'
    _ApplyMap = {
        # FieldName: (xpathStr, createBool);
        'active_table':('/configuration/egress/tables/@active',0),
        'mpeg_pat_rate':('/configuration/egress/tables/mpeg/pat/rate',1),
        'mpeg_pmt_rate': ('/configuration/egress/tables/mpeg/pmt/rate',1),
        'mpeg_cat_rate':('/configuration/egress/tables/mpeg/cat/rate',1),
	    'mpeg_pat_transport_stream_id':('/configuration/egress/tables/mpeg/pat/transport_stream_id',1),
        'pat_transport_stream_id':('/configuration/egress/tables/mpeg/pat/transport_stream_id',1),
        'pat_network_pid':('/configuration/egress/tables/mpeg/pat/network_pid',1),
        'pmt_base_pid':('/configuration/egress/tables/mpeg/pmt/base_pid',1),
        'dvb_nit_enable':('/configuration/egress/tables/dvb/nit/enable',1),
        'dvb_nit_rate':('/configuration/egress/tables/dvb/nit/rate',1),
        'dvb_nit_network_name':('/configuration/egress/tables/dvb/nit/network_name',1),
        'dvb_nit_network_id':('/configuration/egress/tables/dvb/nit/network_id',1),
        'dvb_nit_orig_network_id':('/configuration/egress/tables/dvb/nit/original_network_id',1),
        # NOTE: (JPT) I haven't figured out a way to dynamically figure out how many transport streams there are?
        "dvb/nit/transport_stream[@index='1']/frequency":("/configuration/egress/tables/dvb/nit/transport_stream[@index='1']/frequency",0),
        "dvb/nit/transport_stream[@index='1']/symbol_rate":("/configuration/egress/tables/dvb/nit/transport_stream[@index='1']/symbol_rate",0),
        "dvb/nit/transport_stream[@index='1']/modulation_type":("/configuration/egress/tables/dvb/nit/transport_stream[@index='1']/modulation_type",0),
        "delivery_descriptor":("/configuration/egress/tables/dvb/nit/transport_stream[@index='1']/delivery_descriptor", 0),
        "polarization":("/configuration/egress/tables/dvb/nit/transport_stream[@index='1']/polarization",0),
        "east_west":("/configuration/egress/tables/dvb/nit/transport_stream[@index='1']/east_west",0),
        "dvb/nit/transport_stream[@index='1']/orbital_position":("/configuration/egress/tables/dvb/nit/transport_stream[@index='1']/orbital_position",0),
        "dvb/nit/transport_stream[@index='1']/center_frequency":("/configuration/egress/tables/dvb/nit/transport_stream[@index='1']/center_frequency",0),
        "bandwidth":("/configuration/egress/tables/dvb/nit/transport_stream[@index='1']/bandwidth",0),
        "constellation":("/configuration/egress/tables/dvb/nit/transport_stream[@index='1']/constellation",0),
        "hierarchy_information":("/configuration/egress/tables/dvb/nit/transport_stream[@index='1']/hierarchy_information",0),
        "code_rate_HP_stream":("/configuration/egress/tables/dvb/nit/transport_stream[@index='1']/code_rate_HP_stream",0),
        "code_rate_LP_stream":("/configuration/egress/tables/dvb/nit/transport_stream[@index='1']/code_rate_LP_stream",0),
        "guard_interval":("/configuration/egress/tables/dvb/nit/transport_stream[@index='1']/guard_interval",0),
        "transmission_mode":("/configuration/egress/tables/dvb/nit/transport_stream[@index='1']/transmission_mode",0),
        "other_frequency_flag":("/configuration/egress/tables/dvb/nit/transport_stream[@index='1']/other_frequency_flag",0),
        'dvb_sdt_enable':('/configuration/egress/tables/dvb/sdt/enable',1),
        'dvb_sdt_rate':('/configuration/egress/tables/dvb/sdt/rate',1),
        'dvb_tdt_enable':('/configuration/egress/tables/dvb/tdt/enable',1),
        'dvb_tdt_rate':('/configuration/egress/tables/dvb/tdt/rate',1),
        'dvb_eit_enable':('/configuration/egress/tables/dvb/eit/enable',1),
        'dvb_eit_rate':('/configuration/egress/tables/dvb/eit/rate',1),
        'psip_mode':('/configuration/egress/tables/atsc/psip/table_mode',1),
        'psip_vct_rate':('/configuration/egress/tables/atsc/psip/vct/rate',1),
        'psip_vct_primary_language':('/configuration/egress/tables/atsc/psip/vct/primary_language',1),
        'psip_vct_secondary_language':('/configuration/egress/tables/atsc/psip/vct/secondary_language',1),
        'psip_vct_major_channel':('/configuration/egress/tables/atsc/psip/vct/major_channel',1),
        'psip_vct_minor_channel':('/configuration/egress/tables/atsc/psip/vct/minor_channel',1),
        'psip_vct_modulation_mode':('/configuration/egress/tables/atsc/psip/vct/modulation_mode',1),
        'psip_vct_carrier_frequency':('/configuration/egress/tables/atsc/psip/vct/carrier_frequency',1),
        'psip_mgt_rate':('/configuration/egress/tables/atsc/psip/mgt/rate',1),
        'psip_stt_rate':('/configuration/egress/tables/atsc/psip/stt/rate',1),
        'psip_rrt_rate':('/configuration/egress/tables/atsc/psip/rrt/rate',1),
        'psip_eit_rate':('/configuration/egress/tables/atsc/psip/eit/rate',1),
        'inter_table_enable':('/configuration/egress/tables/enableInterTables',1),
        'inter_table_master':('/configuration/egress/tables/enableInterMaster',1),
        }
    
    def createXpath(self, req, path):
        # get parentPath, child from path
        t = string.split(path, '/')
        parentPath = string.join(t[:-1], '/')
        child = t[-1]
        parentNode = self._muxconfig.xpathEval2(parentPath)
        if len(parentNode) == 0:
            parentNode = [self.createXpath(req, parentNode)]
        return parentNode[0].newChild(None, child, None)
        
    def setParam(self, req, key):
        if self._ApplyMap.has_key(key):
            xpath, create = self._ApplyMap[key];
            nodes = self._muxconfig.xpathEval2(xpath);
            if len(nodes) >= 1:
                nodes[0].setContent(req.params[key])
            elif create:
                nodes = [self.createXpath(req, xpath)]
                if len(nodes) >= 1:
                    nodes[0].setContent(req.params[key])
            else:
                req.error('xpath does not exist\n')
        else:
            req.error('Unknown field: %s' % (key))
            
    def apply(self, req):
        Error = 0       #Error tracking variable
        TZError = 1     #Time Zone Error
        CCError = 2     #Country code error 
        try:
            # Some params need to be "conditioned" to prevent erroneous error logs.
#            del req.params['submit.x']
#            del req.params['submit.y']
#            del req.params['action']
            if req.params.has_key('active_table'):
    #            replaceContentAttr(muxconfig, 'tables', 'active', req.params['active_table'].value)
            #    tables = self._muxconfig.xpathEval2('configuration/egress/tables')[0]
                active_table = req.params['active_table']
            #    tables.setProp('active', active_table)
#            if (active_table == 'MPEG'):
#                if req.params.has_key('mpeg_pat_rate'):
#                    req.params['pat_rate'] = req.params['mpeg_pat_rate']
#                if req.params.has_key('mpeg_pmt_rate'):
#                    req.params['pmt_rate'] = req.params['mpeg_pmt_rate']
#            elif (active_table == 'DVB'):
#                if req.params.has_key('dvb_pat_rate'):
#                    req.params['pat_rate'] = req.params['dvb_pat_rate']
#                if req.params.has_key('dvb_pmt_rate'):
#                    req.params['pmt_rate'] = req.params['dvb_pmt_rate']
#            elif (active_table == 'ATSC'):
#                if req.params.has_key('atsc_pat_rate'):
#                    req.params['pat_rate'] = req.params['atsc_pat_rate']
#                if req.params.has_key('atsc_pmt_rate'):
#                    req.params['pmt_rate'] = req.params['atsc_pmt_rate']
#            del req.params['mpeg_pat_rate']
#            del req.params['mpeg_pmt_rate']
#            del req.params['dvb_pat_rate']
#            del req.params['dvb_pmt_rate']
#            del req.params['atsc_pat_rate']
#            del req.params['atsc_pmt_rate']

            if (req.params['countrytimezone']):
                if (req.params['countrytimezone'].isdigit()):
                    if(string.atoi(req.params['countrytimezone']) <= 60 and string.atoi(req.params['countrytimezone']) >= 0 ):           
                        for node in self._muxconfig.xpathEval2("/configuration/egress/tables[@active='DVB']/dvb/tot/country_time_zone"):
                            node.setContent(req.params['countrytimezone'])
                        self._muxconfig.saveFormatFile(PATH_XML_DOCS + self._configFile, 1)
                        self._muxconfig.saveFormatFile(PATH_XML_DOCS + 'webref.xml', 1)   
                    else:
                        Error = TZError 
                else:
                    Error = TZError
                if (req.params['countrycode']): 
                    if(len(req.params['countrycode']) == 3):           
                        for node in self._muxconfig.xpathEval2("/configuration/egress/tables[@active='DVB']/dvb/tot/iso3166_country_code"):
                            node.setContent(req.params['countrycode'])
                        self._muxconfig.saveFormatFile(PATH_XML_DOCS + self._configFile, 1)
                        self._muxconfig.saveFormatFile(PATH_XML_DOCS + 'webref.xml', 1)   
                    else:
                        if Error == TZError:
                            Error = TZError+CCError #Time zone and Country code error
                        else:
                            Error = CCError     

            for key in req.params:
                self.setParam(req, key)
            self._muxconfig.saveFormatFile(PATH_XML_DOCS + self._configFile, 1)
            self._muxconfig.saveFormatFile(PATH_XML_DOCS + 'webref.xml', 1)
            #muxconfig.saveFile(PATH_XML_DOCS + self._configFile)
    #        print '<body><a href="../cgi-bin/tablesview.py">Success</a></body>'
            #req.set_header('Content-Type', 'text/html')
            #req.write(MESSAGE_FORMAT_PAGE % ('tables.py', 'Success'))
            result={
                    TZError:'Invalid Time Zone (needs to be 0-60)', 
                    CCError:'Invalid Country Code (needs to be three characters)',
                    TZError+CCError:'Invalid Time Zone (needs to be 0-60) and Inavalid Country Code (needs to be three characters)',
                   }
            self._message = result.get(Error,'Apply Successful')
            self.view(req)
        except Exception, e:
            req.set_header('Content-Type', 'text/plain')
            req.write('%s\n' % str(e))

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