#!/usr/bin/python3

import argparse
import json
from datetime import datetime, timezone
from urllib.request import urlopen
import dateutil.parser

def discovery(url="http://localhost:8898"):
    ret = {"data": []}
    req = urlopen(url=f"{url}/v1/jobs")
    try:
        for res_value in json.loads(req.read()):
            if not res_value["disabled"]:
                ret["data"].append({"{#SERVICE}": res_value["name"]})
        return json.dumps(ret)
    except Exception as err:
        return f"error: {err}"

def status(url="http://localhost:8898", task_name=""):
    ret = ""
    try:
        req = urlopen(url=f"{url}/v1/jobs/{task_name}")
        ret = json.loads(req.read())["status"]
    except Exception as err:
        return f"error: {err}"
    return ret

def nextrun(url="http://localhost:8898", task_name=""):
    ret = ""
    nrun = ""
    try:
        req = urlopen(url=f"{url}/v1/jobs/{task_name}")
        nraw = json.loads(req.read())["next"]
        nrun = dateutil.parser.parse(nraw)
        now = datetime.now(tz=timezone.utc)
        diff = nrun-now
        ret = str(int(diff.total_seconds()))
    except Exception as err:
        return f"error: {err}"
    return ret

if __name__ == "__main__":
    parser = argparse.ArgumentParser(prog="dkron")
    subparser = parser.add_subparsers(help='sub-command help', dest='option')
    parser_discovery = subparser.add_parser("discovery")
    parser_status = subparser.add_parser("status")
    parser_status.add_argument("task")
    parser_nextrun = subparser.add_parser("nextrun")
    parser_nextrun.add_argument("task")
    args = parser.parse_args()

    if args.option == "discovery":
        disc = discovery()
        print(disc)
    elif args.option == "status":
        sts = status(task_name=args.task)
        print(sts)
    elif args.option == "nextrun":
        nextr = nextrun(task_name=args.task)
        print(nextr)
    else:
        print("No option specified")