from typing import Any, Mapping
from rest_framework_datatables.renderers import DatatablesRenderer as DRFDatatablesRenderer
from rest_framework.renderers import JSONRenderer
from lchttp.json import json_dumps


class FastJSONRenderer(JSONRenderer):
    def render(
        self,
        data: Mapping[str, Any],
        accepted_media_type: str | None = None,
        renderer_context: Mapping[str, Any] | None = None,
    ) -> bytes:
        """
        Render `data` into JSON, returning a bytestring.
        """
        if data is None:
            return bytes()

        renderer_context = renderer_context or {}
        indent = self.get_indent(accepted_media_type or '', renderer_context)
        return json_dumps(data, indent=indent)


class DatatablesRenderer(FastJSONRenderer, DRFDatatablesRenderer):
    """Use FastJson for parsing performance"""

    pass


class SelectFieldRenderer(FastJSONRenderer):
    """
    Serializer console select fields
    """

    format = 'selectfield'
    id_field = 'pk'

    def render(
        self,
        data: Mapping[str, Any],
        accepted_media_type: str | None = None,
        renderer_context: Mapping[str, Any] | None = None,
    ) -> bytes:
        if data:
            data = dict(data)
            results = []

            for row in data.pop('results', []):
                results.append({
                    'id': row[self.id_field],
                    'text': row.get('select_field_name', row.get('name', 'N/A')),
                })

            data['results'] = results

        return super().render(data, accepted_media_type, renderer_context)


class APISelectFieldRenderer(SelectFieldRenderer):
    """
    Serializer for Push / Pull records from Sync Publishers / Subscribers
    """

    format = 'apiselectfield'
    id_field = 'cid'


__all__ = (
    'DatatablesRenderer',
    'FastJSONRenderer',
    'APISelectFieldRenderer',
    'SelectFieldRenderer',
)
