#!/usr/bin/python

import sys
import os
import time
import datetime

if 'QBDIR' in os.environ:
	sys.path.append('%s/api/python' % os.environ['QBDIR']);
elif os.uname()[0] == 'Darwin':
	sys.path.append('/Applications/pfx/qube/api/python');
elif os.uname()[0] == 'Linux':
	sys.path.append('/usr/local/pfx/qube/api/python');
else:
	sys.path.append('c:/program files/pfx/qube/api/python');

import qb


def blockUntil(job, start):
    '''  
    Configure a job to remain blocked until a certain time of day.

    The time value inserted into the callback is seconds since the epoch,
    offset by L{QB_TIME_EPOCH_OFFSET}.

    @param start: A time of day specified in 24-hour format with a colon
    separator, seconds optional.

    @type start: str HH:MM[:SS]

    @raise ValueError: Raised when the start time is incorrectly formatted.
    '''

    if not start.count(':'):
        msg =  '\n\tERROR waitForTime(): the start time must be in HH:MM[:SS] format\n'
        raise ValueError, msg

    if start.count(':') == 1:
        # append seconds if not supplied
        start += ':00'

    (YY, mm, DD, HH, MM, SS)  = time.localtime()[:6]
 
    startTOD = dict(zip(('H', 'M', 'S'), [int(x) for x in start.split(':') ]))
    nowTOD = dict(zip(('H', 'M', 'S'), (HH, MM, SS)))

    startTime = datetime.time(startTOD['H'], startTOD['M'], startTOD['S'])
    nowTime = datetime.time(nowTOD['H'], nowTOD['M'], nowTOD['S']) 

    # determine the start time in seconds since the epoch,
    startDatetime = datetime.datetime(YY, mm, DD, startTOD['H'], startTOD['M'], startTOD['S'])

    # has the start time already passed today?
    # which means we're talking about starting after midnight, so add
    # 1 day...
    if startTime < nowTime: 
        startDatetime = startDatetime + datetime.timedelta(1)
 
    startEpochSec = time.mktime(startDatetime.timetuple())

    # offset the epoch_seconds by the QB_TIME_EPOCH_OFFSET to get a
    # timestamp that the Qube API understands
    qbStartSec = startEpochSec - qb.QB_TIME_EPOCH_OFFSET

    # Now set the job to be blocked at submission time
    job['status'] = 'blocked'

    callback = {
        'triggers': "dummy-time-job-%d" % qbStartSec,
        'language': 'qube',
        'code': 'unblock-self'
    }    
 
    job.setdefault('callbacks', []).append(callback)

    job['notes'] = 'Job will unblock at: %s' % startDatetime.strftime('%Y-%m-%d %X')



def main():
    job = {}
    job['name'] = 'python test job'
    job['cpus'] = 1
    job['prototype'] = 'cmdline'
    
    package = {}
    job['package'] = package
    job['package']['cmdline'] = 'set'

    # express a time of day as 'HH:MM:SS', we'll pick 2 minutes from now
    # you can just as easily enter '20:00' for 8pm
    timeToUnblock = time.strftime('%X', time.localtime(time.time() + 120) )
    print 'Job will be submitted to unblock at: %s' % timeToUnblock
    
    # now configure this job to be submitted blocked and to unblock at that time
    blockUntil(job, timeToUnblock)

    listOfJobsToSubmit = []
    listOfJobsToSubmit.append(job)

    listOfSubmittedJobs = qb.submit(listOfJobsToSubmit)
    for job in listOfSubmittedJobs:
        print job['id']

if __name__ == "__main__":
    main()
    sys.exit(0)
