#!/usr/bin/env jython

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

from ipptopsps import IppToPsps
from skychunk import Skychunk
from odm import Odm
from batch import Batch


'''
PollOdm class
'''
class PollOdm(IppToPsps):

    '''
    Constructor
    '''
    def __init__(self, argv):
        super(PollOdm, self).__init__(argv)

        # get batch and stage args
        if len(sys.argv) > 3: 
            self.BATCHTYPE = sys.argv[2]
            self.STAGE = sys.argv[3]
        else:
            self.printUsage()
            self.exitProgram("incorrect args")

        # create Odm object
        self.odm = Odm(self.logger)

        # get poll time arg
        if len(sys.argv) > 4: self.parsePollTimeArg(sys.argv[4]) 

        if self.STAGE == "all": self.stages = ['unloaded', 'unmergeworthy', 'unmerged']
        else: self.stages = [self.STAGE]

        if self.BATCHTYPE == "all": self.batchTypes = ['IN', 'P2', 'ST', 'OB', 'DF', 'DO', 'FW', 'FO']
        else: self.batchTypes = [self.BATCHTYPE]

        for stage in self.stages: self.logger.infoPair("Checking stage", stage)
        for batchType in self.batchTypes: self.logger.infoPair("Checking batch type", batchType)

    '''
    Run...
    '''
    def run(self):

        while True:

            self.logger.infoSeparator()
            self.logger.infoPair("Skychunk", self.skychunk.name)

            for stage in self.stages: 
                for batchType in self.batchTypes:
                    self.poll(batchType, stage)

            self.checkClientStatus()
            if not self.waitForPollTime(): break

    '''
    Method to actually poll ODM
    '''
    def poll(self, batchType, stage):
     
        

        if stage == "unloaded":
            ids = self.ippToPspsDb.getUnloadedBatchIDs(batchType)
        elif stage == "unmergeworthy":
            ids = self.ippToPspsDb.getUnmergeWorthyBatchIDs(batchType)
        elif stage == "unmerged":
            ids = self.ippToPspsDb.getUnmergedBatchIDs(batchType)
    
        self.logger.infoTitle("Checking %d %s %s batches" % (len(ids), stage, batchType))
    
        results = {}
        newLoaded = 0
        newMergeWorthy = 0
        newMerged = 0
    
        self.logger.info("+-----------+----------------+----------------+----------------+----------------+----------------+----------------+")
        self.logger.info("|   Batch   | Loaded to ODM  |  Merge worthy  |     Merged     |   New loaded   |New merge worthy|   New merged   |")
        self.logger.info("+-----------+----------------+----------------+----------------+----------------+----------------+----------------+")
        for id in ids:
    
            if self.odm.checkBatch(id, results):
               self.ippToPspsDb.updateOdmStatus(id, results)
    
               if stage == "unloaded":
                   if results['LOADEDTOODM'] == 1: newLoaded = newLoaded + 1
                   if results['MERGEWORTHY'] == 1: newMergeWorthy = newMergeWorthy + 1
                   if results['MERGED'] == 1: newMerged = newMerged + 1
    
               elif stage == "unmergeworthy":
                   if results['MERGEWORTHY'] == 1: newMergeWorthy = newMergeWorthy + 1
                   if results['MERGED'] == 1: newMerged = newMerged + 1

               elif stage == "unmerged":
                   if results['MERGED'] == 1: newMerged = newMerged + 1
    
               self.logger.info("| %9s | %14d | %14d | %14d | %14d | %14d | %14d |" %
                       (Batch.getNameFromID(id),
                            results['LOADEDTOODM'],
                    results['MERGEWORTHY'],
                        results['MERGED'],
                        newLoaded,
                        newMergeWorthy,
                        newMerged))
    
    
            else:
                    self.logger.info("| %9s | failed to poll ODM                                                                                  |" % Batch.getNameFromID(id))
    
        self.logger.info("+-----------+----------------+----------------+----------------+----------------+----------------+----------------+")
    

    '''
    Overrides base-class version
    '''
    def printUsage(self):
        super(PollOdm, self).printUsage("<IN|P2|ST|OB|DF|DO|FW|FO|all> <unloaded|unmergeworthy|unmerged|all> [hours]")
    
    
'''
Program starts here
'''
try:
    pollodm = PollOdm(sys.argv)
    pollodm.run()
    pollodm.exitProgram("completed")
except: pass
