import sys

from pslogger import PSLogger
import logging
from xml.etree.ElementTree import ElementTree, Element, tostring

from ipptopspsdb import IppToPspsDb
from datastore import Datastore
from batch import Batch


'''
A program that republishes a bath to the datastore.

It first 'resets' the batch in the ippToPsps database, i.e. pretends it has never been published, then re-publishes it to the datastore
'''
if len(sys.argv) > 2: 
    CONFIG  = sys.argv[1]
    BATCHID  = int(sys.argv[2])
else:
    print "** Usage: " + sys.argv[0] + " <configPath> <batchid>"
    sys.exit(1)

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

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

ippToPspsDb = IppToPspsDb(logger, configDoc)
datastore = Datastore(logger, configDoc, ippToPspsDb)

DVOLABEL = configDoc.find("dvo/gpc1Label").text
EPOCH = configDoc.find("options/epoch").text
BASEPATH = configDoc.find("localOutPath").text
DATASTOREPRODUCT = configDoc.find("datastore/product").text

logger.infoTitle("Batch republisher")
logger.infoPair("Loading epoch", EPOCH)
logger.infoPair("DVO label", DVOLABEL)


batchName = Batch.getNameFromID(BATCHID)
BATCHTYPE = ippToPspsDb.getBatchType(BATCHID)
subDir = Batch.getSubDir(BASEPATH, BATCHTYPE, DVOLABEL)
tarballFile = Batch.getTarballFile(BATCHID)

logger.infoPair("batch ID", "%d" % BATCHID)
logger.infoPair("batchname", batchName)
logger.infoPair("batch type", BATCHTYPE)
logger.infoPair("subdir", subDir)
logger.infoPair("tarballfile", tarballFile)
logger.infoPair("Reseting batch in database", "%d" % BATCHID)
ippToPspsDb.resetBatch(BATCHID)
logger.infoPair("publishing to", DATASTOREPRODUCT)
Batch.publishToDatastore(datastore, BATCHID, batchName, subDir, tarballFile)



