#!/usr/bin/env jython

import re
import sys
import tempfile
from xml.etree.ElementTree import ElementTree, Element, tostring
from subprocess import call, PIPE, Popen

from batch import Batch

'''
Class for using DXLayer webservice
'''
class DXLayer(object):

    '''
    Constructor
    '''
    def __init__(self, logger):

        self.logger = logger

    '''
    Delete's a batch from the DXLayer
    '''
    def deleteBatch(self, batchID):
        #HAF This is really lazy to do this way, but for the time, will check both dx layers and try the first, if no go try the second.

        batch = Batch.getNameFromID(batchID)

        tempFile = tempfile.NamedTemporaryFile(mode='w+b')

        p = Popen("deleteFromDXLayer.pl -b " + batch + " -f " + tempFile.name, 
                shell=True, 
                stdout=PIPE)
        p.wait()
       
        if p.returncode != 0:
           self.logger.infoPair("DXLayer webservice", "failed")
           return 0
        else:
           self.logger.infoPair("DXLayer webservice", "successful")

        ret = self.decodeDXLayerResponse(tempFile.name)

        tempFile.close()
        p.stdout.close()

        if ret: self.logger.infoPair("Deleted batch from DXLayer 1", batch) 
        else: self.logger.infoPair("Unable to delete batch from DXLayer 1" , batch)


       

        tempFile = tempfile.NamedTemporaryFile(mode='w+b')

        p = Popen("deleteFromDXLayer2.pl -b " + batch + " -f " + tempFile.name, 
                shell=True, 
                stdout=PIPE)
        p.wait()
       
        if p.returncode != 0:
           self.logger.infoPair("DXLayer webservice", "failed")
           return 0
        else:
           self.logger.debugPair("DXLayer webservice", "successful")

        ret = self.decodeDXLayerResponse(tempFile.name)

        tempFile.close()
        p.stdout.close()

        if ret: self.logger.infoPair("Deleted batch from DXLayer 2", batch) 
        else: self.logger.infoPair("Unable to delete batch from DXLayer 2" , batch)




        return ret


    '''
    Parses the XML returned from the DXLayer webservice call
    '''
    def decodeDXLayerResponse(self, dxLayerResponseFile):

        doc = ElementTree(file=dxLayerResponseFile)

        ret = False
        try:
            MESSAGE = doc.find("Rows/Row/Value").text

            #print "MESSAGE " + MESSAGE
            if re.search("Path not found", MESSAGE):
                ret = True
            elif re.search("Deleted", MESSAGE): 
                ret = True
                
        except:
            self.logger.error("Cannot read DXLayer response file")
            ret = False
 
        return ret
