import sys
import jsonschema
from flask import request

from helper_functions import set_data
from logger_module.package_logger import print_log


class SchemaLoading:

    @staticmethod
    def schema_validation(schema_body, endpoint, method):
        data = request.get_json
        schema = schema_body.get('paths').get(endpoint).get(method).get(
            'requestBody', {}).get('content')
        try:
            if schema:
                jsonschema.validate(instance=data, schema=schema)
                print("Data is valid.", file=sys.stderr)
            return {"validation": True, "cf_code": "CF200", 'return_code': '00000'}
        except jsonschema.exceptions.ValidationError as e:
            try:
                if not e.schema.get('message'):
                    path = list(e.path)
                    message_key = e.message.split(" is")[0].replace("'", "").strip()
                    if path:
                        # val = schema.get('properties').get(path[0]).get('properties').get(message_key)
                        val = schema
                        for keys in path:
                            if not isinstance(keys, int):
                                val = val.get('properties').get(keys)
                        val = val.get('items').get('properties').get(message_key) if val.get('type') == 'array' else val.get('properties').get(message_key)
                    else:
                        val = schema.get('properties').get(message_key)
                    error_message = val.get('message').get('message', 'Unknown error')
                    return_code = val.get('message').get('return_code', 'CF500')
                    set_data('response', val.get('message'))
                    if return_code == 'CF500':
                        return {'cf_code': return_code}
                else:
                    set_data('response', e.schema.get('message'))
                    error_message = e.schema.get('message').get('message')
                    return_code = e.schema.get('message').get('return_code')
                return {"validation": False, "message": error_message, "cf_code": "CF300", 'return_code': return_code}
            except Exception as ex:
                print_log(str(ex))
                return {'cf_code': 'CF500'}

