import sys,argparse,json,time
sys.path.insert(0, './classes/')

import cohesityAPI as cohesity

def GetArgs():
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('--cluster', '-c', type=str, action='store')
    parser.add_argument('--vcenter', '-v', type=str, action='store')
    parser.add_argument('--job', '-j', type=str, action='store')
    parser.add_argument('--help', '-h', action='store_true')
    return (parser.parse_args())

def PrintHelp():
    print("\nBasic Usage:")
    print("Set OS environment variables ITD_SHAREPOINT_PASS and ITD_SHAREPOINT_USER")
    print("\nExample:")
    print(r"$ export COHESITY_USER=\"NDGOV\jDoe\"") 
    print("$ export COHESITY_PASS=\"1Lik3Jane\"")
    print("\n python3 <SCRIPT_NAME> -c cluster1.domain.tld [ -v vCenter.domain.tld ] [ -j protectionJobName ]")
    print("\t -c FQDN of Cohesity cluster address")
    print("\t -v FQDN of vCenter Server, used in conjuntion with -t kVMware ")
    print("\t -j Cohesity job name")
    print("\t -h Prints this help message")

args = GetArgs()

if args.help:
    PrintHelp()

if not args.cluster:
    sys.exit("Error: Specify Cohesity cluster fqdn with -c parameter.")
else:
    cluster = cohesity.API(args.cluster) 
    authToken = cluster.GetAuthToken()
    cluster.UpdateHeaders(authToken['accessToken'])

if args.vcenter:
    vmSources = cluster.GetFilteredRequest("/public/protectionSources", "?environments=kVMware")

    for source in vmSources:
        if source['protectionSource']['name'] == args.vcenter:
            vCenter = source
            vCenterID = source['protectionSource']['id']
            break

    if args.job:
        # Get the details of a single job
        vmJobs = cluster.GetFilteredRequest("/public/protectionJobs", "?names=" + args.job)
    else:
        # Get the details of all jobs under a vCenter
        vmJobs = cluster.GetFilteredRequest("/public/protectionJobs", "?environments=kVMware")

    uniqueJobs = {job['id'] : job for job in vmJobs}.values()

# Do stuff with the JSON data
# Example:
    if args.pause:
        pausedJobs = []
        for job in uniqueJobs:
            if job['parentSourceId'] != vCenterID:
                print("not vcenter")
                continue

            elif "isDeleted" in job:
                continue

            elif "isPaused" in job:
                if job['isPaused']:
                    pausedJobs.append(job)
                    continue

            print("Pausing: " + job['name']) 
            resp = cluster.PauseJob(job['id'])

        print("The following jobs were previously paused before this operation.")
        for pJob in pausedJobs:
            print(pJob['name'])

    if args.resume:
        for job in uniqueJobs:
            if job['parentSourceId'] != vCenterID:
                continue

            elif "isDeleted" in job:
                continue

            print("Resuming: " + job['name']) 
            resp = cluster.ResumeJob(job['id'])
