#!/usr/bin/python

import argparse, os, re, subprocess, sys, time
from MythTV import MythDB, Job

mythDB = MythDB()
cursor = mythDB.cursor()

def set_cmds(cmdargs,job):
    #print "Setting cmds on job %s to %s" %(cmdargs.jobid,cmdargs.cmd)
    cursor.execute("update jobqueue set cmds = '%s' where id = '%s'" %(cmdargs.cmd,cmdargs.jobid))

def set_comment(cmdargs,job):
    #print "Setting comment on job %s to %s" %(cmdargs.jobid,cmdargs.comment)
    job.setComment("%s" %cmdargs.comment)

def set_status(cmdargs,job):
    #print "Setting status on job %s to %s" %(cmdargs.jobid,cmdargs.status)
    job.setStatus("%s" %cmdargs.status)

def run_cursor(cmdargs):
    cursor.execute("%s" %cmdargs.man_cursor)
    results=cursor.fetchone()
    print(results[0])

def usage():
    line = '''
    jobqueue_helper.py provides MythTV job queue functions
    using python bindings for bash scripts.
    Use jobqueue_helper.py -h to see options.
    '''
    print(line)
    sys.exit(0)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-cs', '--comment_set', action='store', dest='comment', help='Set the comment of the jobid')
    parser.add_argument('-cmds', '--cmd_set', type=int, default=77777, action='store', dest='cmd', help='Set the cmd of the jobid')
    parser.add_argument('-ss', '--status_set', type=int, action='store', dest='status', help='Set the status of the jobid')
    action = parser.add_mutually_exclusive_group(required=True)
    action.add_argument('-j', '--jobid', type=int, help='jobid of the job to control')
    action.add_argument('-m', '--man_cursor', action='store', dest='man_cursor', help='Manual mysql cursor command')
    action.add_argument('-u', '--usage', action='store_true', help='Print usage instructions.')

    cmdargs = parser.parse_args()

    if cmdargs.usage:
        usage()

    if cmdargs.jobid:
        job = Job(cmdargs.jobid)

    if cmdargs.comment:
        set_comment(cmdargs, job)

    if cmdargs.status:
        set_status(cmdargs, job)

    if cmdargs.cmd != 77777:
        set_cmds(cmdargs, job)

    if cmdargs.man_cursor:
        run_cursor(cmdargs)
