# coding: utf-8

import json


class ApiResponse(object):
    def __init__(self, api_request, response):
        self.api_request = api_request
        self.response = response

    def serialize(self):
        try:
            body = json.loads(self.response.content)
        except ValueError:
            body = self.response.content

        serialized = {
            'status_code': self.response.status_code,
            'headers': dict(self.response.items()),
            'body': body,
        }

        if self.api_request.id:
            serialized['id'] = self.api_request.id

        return serialized

    def is_warning(self, tolerate_4xx=False):
        result = False
        if tolerate_4xx:
            result = 400 <= self.response.status_code < 500
        return result

    def is_error(self, tolerate_4xx=False):
        if tolerate_4xx:
            result = self.response.status_code >= 500
        else:
            result = not (200 <= self.response.status_code < 300)
        return result
