# -*- coding: utf-8 -*-
from requests import RequestException

from events.surveyme_integration.services.http.action_processors import PostHTTPActionProcessor


class PostJSONRPCActionProcessor(PostHTTPActionProcessor):
    force_multipart = False
    convert_body_to_json = True

    def is_need_status_checking(self, response):
        return False

    def raise_exception_if_needed_based_on_response(self, response):
        # todo: test me
        """
        HTTP       JSON-RPC        DESC
        500        -32700          Parse error.
        400        -32600          Invalid Request.
        404        -32601          Method not found.
        500        -32602          Invalid params.
        500        -32603          Internal error.
        500        -32099..-32000  Server error.
        """
        if response:
            try:
                response_data = response.json()
            except ValueError:  # json decoding error
                pass
            else:
                if response_data and 'error' in response_data:
                    if response_data['error'].get('code') in [
                        -32700,
                        -32600,
                        -32602,
                    ]:
                        raise Exception(response_data['error'])
                    else:
                        raise RequestException(response_data['error'])
        super(PostJSONRPCActionProcessor, self).raise_exception_if_needed_based_on_response(response=response)
