#!/usr/bin/env python3

#
# Development Order #3:
# 
# This file will determine if this tool can run a test based on a test spec.
#
# Be sure to edit line 19, inserting the names of the tests the tool
# should be compatible with.
# 

# exit statuses should be different based on error

import pscheduler

from urllib.parse import urlparse

from utilities import file_ok


json = pscheduler.json_load(exit_on_error=True);


try:
    test_type = json["type"]
except KeyError:
    pscheduler.succeed_json({
        "can-run": False,
        "reasons": [ "Missing test type" ]
    })

if test_type != "http":
    pscheduler.succeed_json({
        "can-run": False,
        "reasons": [ "Unsupported test type" ]
    })



MAX_SCHEMA = 3

try:
    pscheduler.json_check_schema(json["spec"], MAX_SCHEMA)
except ValueError as ex:
    # Schema check failed
    pscheduler.succeed_json({
        "can-run": False,
        "reasons": [str(ex)]
    })
except KeyError:
    # Data was missing
    pscheduler.succeed_json({
        "can-run": False,
        "reasons": ["Missing data in test specification"]
    })


try:
    test_type = json['type']
    spec = json['spec']
    source = spec['url']
    keep_content = spec.get('keep-content', None)
except KeyError:
    pscheduler.succeed_json({
        'can-run': False,
        'reasons': [ 'Missing data in input' ]
    })

if test_type != 'http':
    pscheduler.succeed_json({
        'can-run': False,
        'reasons': [ 'Unsupported test type' ]
    })

reasons = []

parsed_url = urlparse(source)

if parsed_url.scheme == 'file':

    if keep_content is not None:
        reasons.append('Cannot keep content from file:// URLs')

    if spec.get("parse", None):
        reasons.append('Cannot parse content from file:// URLs')

    reasons.extend(file_ok(parsed_url.path))


pscheduler.succeed_json(
    { 'can-run': False, 'reasons': reasons } if reasons else { 'can-run': True }
)

