#!/usr/bin/env python3
#
# Determine if this tool can run a test based on a test spec.
#

import datetime
import sys

import pscheduler

json = pscheduler.json_load(exit_on_error=True);


# TODO: Should be checking the package schema and the task spec schema.

try:
    if json['type'] not in [ 'idle', 'idleex' ]:
        pscheduler.succeed_json({
            "can-run": False,
            "reasons": [ "Unsupported test type" ]
        })
except KeyError:
    pscheduler.succeed_json({
        "can-run": False,
        "reasons": [ "Missing test type" ]
    })


try:
    spec = json["spec"]
    pscheduler.json_check_schema(spec, 2)
except KeyError:
    pscheduler.succeed_json({
        "can-run": False,
        "reasons": ["Missing test specification"]
    })
except ValueError as ex:
    pscheduler.succeed_json({
        "can-run": False,
        "reasons": [str(ex)]
    })


errors = []


# This tool has a (forced) quirk that makes it not sleep for less than
# 30 seconds or more than one hour.

duration = pscheduler.iso8601_as_timedelta(spec['duration'])
if duration is not None:
    if duration < datetime.timedelta(seconds=15):
        errors.append("Won't sleep for less than 15 seconds.")
    if duration > datetime.timedelta(hours=1):
        errors.append("Won't sleep for more than one hour.")


result = {
    "can-run": len(errors) == 0
}

if len(errors) > 0:
    result["reasons"] = errors

pscheduler.succeed_json(result)
