import functools
import json

from flask import request
from marshmallow import Schema, ValidationError

from fullstack.response import ResponseCode, response_result
from app.setting import config

def validate_schema(schema_class: Schema):
    def decorator(view_func):
        @functools.wraps(view_func)
        def inner(*args, **kwargs):
            try:
                if request.method == "GET":
                    form_data = request.args
                elif request.method == "POST":
                    if request.content_type and request.content_type.startswith('application/json'):
                        form_data = request.json
                    elif request.content_type and request.content_type.startswith('application/x-www-form-urlencoded'):
                        form_data = request.values
                    elif request.content_type and request.content_type.startswith('multipart/form-data'):
                        form_data = request.form
                    else:
                        form_data = json.loads(request.data)

                data = schema_class().load(form_data)
                request.schema_data = data
                print(request.schema_data)
            except ValidationError as e:
                if config['DEBUG']:
                    return response_result(ResponseCode.PARAMETER_ERROR, e.messages if config['DEBUG'] else None)
            return view_func(*args, **kwargs)
        return inner
    return decorator
