#!/usr/bin/env python3
#
# Run a test.  Just the test spec is provided on stdin.
#

import datetime
import json
import sys
import time

import pscheduler

log = pscheduler.Log(prefix="tool-sleep", quiet=True)

input = pscheduler.json_load(exit_on_error=True);

# Validate the input

# TODO: This should probably be in a module that can be shared with
# can-run.

# TODO: Be more thorough.


try:
    duration_iso = input['test']['spec']['duration']
except KeyError:
    pscheduler.fail('Unable to find duration in input')


duration = pscheduler.iso8601_as_timedelta(duration_iso)
if duration is None:
    pscheduler.fail_other(2, "Missing or invalid duration " + duration_iso)
else:
    if duration < datetime.timedelta(seconds=15):
        pscheduler.fail("Won't sleep for such a short time.")


# Perform the test

# The output is just mocked up since there's no real tool being run.

output = ''

try:
    output += input['test']['spec']['starting-comment'] + '\n'
except KeyError:
    pass

try:
    start_at = input['schedule']['start']
    log.debug("Sleeping until %s", start_at)
    pscheduler.sleep_until(start_at)
    log.debug("Starting")
except KeyError:
    pscheduler.fail("Unable to find start time in input")

time.sleep(pscheduler.timedelta_as_seconds(duration))

try:
    output += input['test']['spec']['parting-comment'] + '\n'
except KeyError:
    pass



#
# Produce results
#

results = {
    'succeeded': True,
    'diags': output,
    'error': '',
    'result': { 'time-slept': pscheduler.timedelta_as_iso8601(duration) }
}

pscheduler.succeed_json(results)
