import json


def get_schema():
    key = "monitoring-agent"
    schema = {
        "description": "Monitoring agent configuration",
        "type": "object",
        "properties": {
            "response-prefix": {
                "description": "",
                "type": "string"
            },
            "onboarding-topic": {
                "description": "",
                "type": "string"
            },
            "location": {
                "description": "",
                "type": "string"
            },
            "room": {
                "description": "",
                "type": "string"
            },
            "device": {
                "description": "",
                "type": "string"
            },
            "gid": {
                "description": "",
                "type": ["number", "string"]
            },
            "name": {
                "description": "",
                "type": "string"
            },
            "description": {
                "description": "",
                "type": "string"
            },
            "log-level": {
                "description": "Log level to be used.",
                "type": "string",
                "enum": ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
            },
            "restart-onboarding": {
                "description": "timeout in seconds after which an restart onboarding request is restarted. "
                               "example: 60 seconds.",
                "type": "integer"
            }
        },
        "required": ["restart-onboarding", "response-prefix", "onboarding-topic", "location", "room", "device", "name",
                     "description", "log-level"]
    }

    return key, schema


def dump_schema(filename):
    """
    Dumps the latest schema to the provided file but only iff the contents differ. If no file is found, a new file
    will be generated.

    :param filename - path to autogenerated config schema json file
    """
    k, s = get_schema()
    schema = {k: s}
    new_schema = json.dumps(schema, indent=4)

    try:
        with open(filename, 'r') as f:
            old_schema = f.read()
    except OSError:
        old_schema = ""

    if new_schema != old_schema:
        print("updating {} to latest schema.".format(filename))
        with open(filename, 'w') as f:
           f.write(new_schema)