#!/usr/bin/env jython

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

from batch import Batch

'''
Class for ippToPsps database connectivity
'''
class Odm(object):

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

        self.logger = logger

    '''
    Checks a batch with the ODM
    '''
    def checkBatch(self, batchID, results):

        batch = Batch.getNameFromID(batchID)

        tempFile = tempfile.NamedTemporaryFile(mode='w+b')
        self.logger.infoPair("checkOdmStatus.pl -b " + batch + " -f " + tempFile.name, "")
        p = Popen("checkOdmStatus.pl -b " + batch + " -f " + tempFile.name, 
                shell=True, 
                stdout=PIPE,
                close_fds=True)
        p.wait()
       
        if p.returncode != 0:
           self.logger.debugPair("ODM polling", "failed")
           return 0
        else:
           self.logger.debugPair("ODM polling", "successful")

        ret = self.decodeODMResponse(tempFile.name, results)

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


        if not ret: self.logger.debugPair("Cannot read ODM file for batch", "%d" % batchID)

        return ret

    '''
    Parsed the XML returned from the ODM SOAP call
    '''
    def decodeODMResponse(self, odmResponseFile, results):

        doc = ElementTree(file=odmResponseFile)

        loadedToODM = 0
        mergeWorthy = 0
        merged = 0

        try:
            NAMESPACE = "PanSTARRS.Services.OdmWebService"
            STATE = doc.find("{%s}OdmBatchState/{%s}BatchState" % (NAMESPACE, NAMESPACE)).text
            MESSAGE = doc.find("{%s}OdmBatchState/{%s}Message" % (NAMESPACE, NAMESPACE)).text
            results['MESSAGE'] = MESSAGE
            results['DETAILS'] = "None"

            # we assume that batches 'OnHold' are failed as it is very rare for such
            # batches to have there state changed
            if re.search("failed", STATE) or re.search("OnHold", MESSAGE):
                loadedToODM = -1
                DETAILS = doc.find("{%s}OdmBatchState/{%s}Details" % (NAMESPACE, NAMESPACE)).text
                results['DETAILS'] = DETAILS
            elif re.search("processing", STATE):
                loadedToODM = 1
            if re.search("MergeWorthy", MESSAGE): 
                loadedToODM = 1
                mergeWorthy = 1
            if re.search("Merge[1-9]Completed", MESSAGE): 
                loadedToODM = 1
                mergeWorthy = 1
                merged = 1
#            if re.search("released", STATE):
#                loadedToODM = 1
#                mergeWorthy = 1
#                merged = 1
#            if re.search("released", MESSAGE):
#                loadedToODM = 1
#                mergeWorthy = 1
#                merged = 1
        except:
            pass

        results['LOADEDTOODM'] = loadedToODM
        results['MERGEWORTHY'] = mergeWorthy
        results['MERGED'] = merged

        return 1
