import codecs
from django.conf import settings
from rest_framework.parsers import BaseParser
from rest_framework.exceptions import ParseError
from .renderers import FastJSONRenderer
from lchttp.json import json_loads


class FastJSONParser(BaseParser):
    """
    Parses JSON-serialized data by ``json_loads`` library.
    """

    media_type = 'application/json'
    renderer_class = FastJSONRenderer

    def parse(self, stream, media_type=None, parser_context=None):
        """
        Parses the incoming bytestream as JSON and returns the resulting data.
        """
        parser_context = parser_context or {}
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)

        try:
            decoded_stream = codecs.getreader(encoding)(stream)
            return json_loads(decoded_stream.read())
        except ValueError as exc:
            raise ParseError(f'FastJSON parse error - {exc}') from None


__all__ = [
    'FastJSONParser',
]
