#!/usr/bin/env python
"""Tron Control

Part of the command line interface to the tron daemon. Provides the interface to controlling jobs and runs.
"""
import sys
import os.path
import urllib2
import urlparse
import simplejson
import optparse
import logging

import yaml

from tron import cmd

COMMAND_HELP = (
    ('start', 'Start the selected job, job run or action'),
    ('cancel', 'Cancel the selected job run'),
    ('disable', 'Disable selected job and cancel any outstanding runs'),
    ('enable', 'Enable the selected job and schedule the next run'),
    ('disableall', 'Disable all jobs'),
    ('enableall', 'Enable all jobs'),
    ('fail', 'Mark an UNKNOWN job as having failed'),
    ('succeed', 'Mark an UNKNOWN job as having succeeded'),
)

class TronCtlOptionParser(optparse.OptionParser):
    def format_epilog(self, formatter):
        # We want to include some extra helpful info
        result = []
        result.append(formatter.format_heading("Commands"))
        formatter.indent()
        for cmd, desc in COMMAND_HELP:
            result.append(formatter._format_text(''.join((cmd.ljust(20), desc.ljust(40)))))
            result.append('\n')
        
        result.append('\n')
        return ''.join(result)

log = logging.getLogger('')

def parse_options():
    parser = TronCtlOptionParser("usage: %prog [options] <command> [<job | job run | action>]")
    parser.add_option("--server", action="store", dest="server", help="Server URL to connect to", default=None)
    parser.add_option("--verbose", "-v", action="count", dest="verbose", help="Verbose logging", default=0)
    (options, args) = parser.parse_args(sys.argv)

    if len(args) < 2:
        parser.error("Missing command")

    return options, args[1:]

def edit(options, command, id):
    data = {'command': command}
    status, content = cmd.request(options.server, "/jobs/%s" % id.replace('.', '/'), data=data)

    if status == cmd.OK:
        log.info(content['result'])
        print content['result']
        return True
    else:
        return False

def main():
    """run tronctl"""
    options, args = parse_options()
    cmd.setup_logging(options)

    cmd.load_config(options)
    status, content = cmd.request(options.server, "/")
    if status != cmd.OK or not content:
        log.error("Error connecting to tron server at %s", options.server)
        sys.exit(1)

    ret = edit(options, args[0], args[1] if len(args) > 1 else '')
    cmd.save_config(options)
    if ret:
        sys.exit(0)
    else:
        sys.exit(1)

if __name__ == '__main__':
    main()
