#!/usr/bin/env python3
#
# Validate data for the failer archiver
#

import pscheduler

try:
    json = pscheduler.json_load()
except ValueError as ex:
    pscheduler.succeed_json({
        "valid": False,
        "error": str(ex)
        })

MAX_SCHEMA = 2

SPEC_SCHEMA = {

    "local": {

        "v1": {
            "type": "object",
            "properties": {
                "schema": {" type": "integer", "enum": [ 1 ] },
                "delay": { "$ref": "#/pScheduler/Duration" },
                "fail": { "$ref": "#/pScheduler/Float" },
                "retry": { "$ref": "#/pScheduler/Float" }
            },
            "additionalProperties": False
        },

        "v2": {
            "type": "object",
            "properties": {
                "schema": {" type": "integer", "enum": [ 2 ] },
                "schema": { "$ref": "#/pScheduler/Cardinal" },
                "delay": { "$ref": "#/pScheduler/Duration" },
                "fail": { "$ref": "#/pScheduler/Float" },
                "retry": { "$ref": "#/pScheduler/Float" },
                "badly": { "$ref": "#/pScheduler/Boolean" }
            },
            "required": [
                "schema"
            ],
            "additionalProperties": False
        }

    }
}



schema = json.get("schema", 1)        

# Build a temporary structure with a reference that points
# directly at the validator for the specified version of the
# schema.  Using oneOf or anyOf results in error messages that are
# difficult to decipher.

temp_schema = {
    "local": SPEC_SCHEMA["local"],
    "$ref":"#/local/v%s" % schema
}

valid, error = pscheduler.json_validate(json, temp_schema, max_schema=MAX_SCHEMA)

if not valid:
    pscheduler.succeed_json({
        "valid": False,
        "error": error
        })
    
pscheduler.succeed_json({ "valid": True })
