#!python
"""
Retrieve the UWS status of a given job.

The UWS system is used by VOSpace for asynchronous actions. Normally users do not use or need to use this script.
checkJobPhase is provide for admin usage.

This script is used to retrieve the state of a job using X509 authentication.

"""


import sys
from OpenSSL.rand import status
import vos
import argparse
import os
import logging

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description="Get the status of a UWS job.")

    parser.add_argument("--certfile",
                        help="location of your CADC security certificate file",
                        default=os.path.join(os.getenv("HOME", "."), ".ssl/cadcproxy.pem"))
    parser.add_argument("-v", "--verbose", action='store_const', const=True,
                        help="print some diagnostics")
    parser.add_argument("-d", "--debug", action='store_const', const=True,
                        help="print all diagnositics")
    parser.add_argument("jobURL", action='store', help="The URL of the job to test")


    opt = parser.parse_args()

    if opt.verbose:
        log_level = logging.INFO
    elif opt.debug:
        log_level = logging.DEBUG
    else:
        log_level = logging.ERROR

    logging.getLogger('vos').setLevel(log_level)
    logging.getLogger('vos').addHandler(logging.StreamHandler())

    try:
        client = vos.Client(certFile=opt.certfile)
        sys.stdout.write("%s\n" % client.getJobStatus(opt.jobURL))
    except KeyboardInterrupt:
        sys.stderr.write("Received keyboard interrupt. Execution aborted...\n")
        sys.exit(-1)
    except Exception as e:
        sys.stderr.write(str(e))
        sys.exit(-1)
    sys.exit(0)
