#!/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, max_schema=2);


try:
    if json['type'] != 'simplestream':
        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, 3)
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 = []

# Require that the timeout be at least twice the dawdle interval.

try:
    timeout = pscheduler.iso8601_as_timedelta(spec['timeout'])
except KeyError:
    timeout = None
except ValueError:
    errors.append("Invalid timeout.")

try:
    dawdle = pscheduler.iso8601_as_timedelta(spec['dawdle'])
    if timeout is not None and dawdle * 2 > timeout:
        errors.append("Dawdle duration must be less than half the timeout.")
except KeyError:
    pass  # No dawdle is okay.
except ValueError:
    pscheduler.fail("Invalid dawdle.")    


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

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

pscheduler.succeed_json(result)

