import datetime
import json
import logging

from dateutil import parser
from django.utils import timezone
from rest_framework.renderers import JSONRenderer


logger = logging.getLogger('print')

class CompactJSONRenderer(JSONRenderer):
    """Renderer which serializes to JSON using the most compact JSON representation."""
    def render(self, data, accepted_media_type=None, renderer_context=None):
        if data is None:
            return bytes()

        return json.dumps(data, separators=(',', ':'), cls=self.encoder_class, ensure_ascii=self.ensure_ascii)

def to_datetime(x):
    if x is None or not x:
        return None
    try:
        default_dt = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=timezone.utc)
        return parser.parse(x, default=default_dt)
    except Exception as e:
        logger.error(str(e))
        return None

def to_int(x):
    try:
        return int(x)
    except (ValueError, TypeError) as _:
        return None
