#!/usr/bin/env jython

from datastore import Datastore
import logging
import sys
import getopt
import traceback

from ipptopsps import IppToPsps
from datastore import Datastore
from batch import Batch

'''
BatchRepublisher class

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
'''
class BatchRepublisher(IppToPsps):

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

        if len(sys.argv) < 3:
            self.printUsage()
            self.exitProgram("incorrect args")

        self.datastore = Datastore(self.logger, self.config, self.ippToPspsDb)
        self.BATCHID = int(sys.argv[2])

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

        batchName = Batch.getNameFromID(self.BATCHID)
        batchType = self.ippToPspsDb.getBatchType(self.BATCHID)
        subDir = Batch.getSubDir(self.config.basePath, batchType, self.config.dvoLabel)
        tarballFile = Batch.getTarballFile(self.BATCHID)

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

    '''
    Overrides base-class version
    '''
    def printUsage(self):
        super(BatchRepublisher, self).printUsage("<batchToRepublish>")

'''
Start of program
'''
try:
    batchRepublisher = BatchRepublisher(sys.argv)
    batchRepublisher.run()
    batchRepublisher.exitProgram("completed")
except Exception, e:
    print str(e)
    traceback.print_exc()

