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

import logging.config
from pslogger import PSLogger
from ipptopspsdb import IppToPspsDb
from odm import Odm
from batch import Batch

'''
Method to actually poll ODM
'''
def poll(batchType, stage):
  
    if stage == "unloaded":
        ids = ippToPspsDb.getUnloadedBatchIDs(EPOCH, DVOLABEL, batchType)
    elif stage == "unmergeworthy":
        ids = ippToPspsDb.getUnmergeWorthyBatchIDs(EPOCH, DVOLABEL, batchType)
    elif stage == "unmerged":
        ids = ippToPspsDb.getUnmergedBatchIDs(EPOCH, DVOLABEL, batchType)

    logger.infoTitle("Checking %d %s %s batches" % (len(ids), stage, batchType))

    results = {}
    newLoaded = 0
    newMergeWorthy = 0
    newMerged = 0

    logger.info("+-----------+----------------+----------------+----------------+----------------+----------------+----------------+----------------+")
    logger.info("|   Batch   | Loaded to ODM  |  Load failed   |  Merge worthy  |     Merged     |   New loaded   |New merge worthy|   New merged   |")
    logger.info("+-----------+----------------+----------------+----------------+----------------+----------------+----------------+----------------+")
    for id in ids:

        if odm.checkBatch(id, results):
           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

           logger.info("| %9s | %14d | %14d | %14d | %14d | %14d | %14d | %14d |" %
                   (Batch.getNameFromID(id),
                    results['LOADEDTOODM'],
                    results['LOADFAILED'],
                    results['MERGEWORTHY'],
                    results['MERGED'],
                    newLoaded,
                    newMergeWorthy,
                    newMerged))


        else:
            logger.info("| %9s | failed to poll ODM                                                                                                   |" % Batch.getNameFromID(id))

    logger.info("+-----------+----------------+----------------+----------------+----------------+----------------+----------------+----------------+")


'''
Program starts here
'''
if len(sys.argv) > 3: 
    CONFIG  = sys.argv[1]
    BATCHTYPE = sys.argv[2]
    STAGE = sys.argv[3]
else:
    print "\n** Usage: " + sys.argv[0] + " <configPath> <P2|ST|all> <unloaded|unmergeworthy|unmerged|all> [hours]\n"
    sys.exit(1)

if len(sys.argv) > 4:  
    HOURS = float(sys.argv[4]) 
    SECONDS = HOURS * 60.0 * 60.0
else: 
    SECONDS = None

# open config file
configDoc = ElementTree(file=CONFIG)

# set up logging
logging.setLoggerClass(PSLogger)
logger = logging.getLogger(sys.argv[0])
logger.setup(configDoc, sys.argv[0])

ippToPspsDb = IppToPspsDb(logger, configDoc)
odm = Odm(logger, configDoc)

DVOLABEL = configDoc.find("dvo/gpc1Label").text
EPOCH = configDoc.find("options/epoch").text

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

if BATCHTYPE == "all": batchTypes = ['P2', 'ST']
else: batchTypes = [BATCHTYPE]

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

while True:

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

    if SECONDS: 
        logger.infoPair("Waiting for", "%f hours" % HOURS)
        time.sleep(SECONDS)
    else: break


