#!/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):

        batch = Batch.getNameFromID(batchID)

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

        p = Popen("../perl/deleteFromDXLayer.pl -b " + batch + " -f " + tempFile.name, 
                shell=True, 
                stdout=PIPE)
        p.wait()
       
        if p.returncode != 0:
           self.logger.debugPair("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", batch) 
        else: self.logger.errorPair("Unable to delete batch from DXLayer", 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
