import json
from django.http import HttpResponse
from grid_registrar import get_grid_class

class JsonResponse(HttpResponse):
    """
    Returns a JSON Response

    Takes the content object, json.dumps it and returns it an a response.

    Args:
        content: The object to be serialized into JSON
        mimetype: Response mime type. Default is application/json
        status: HTTP status code. Default is NONE.
        content_type: The response content type. Default is application/json
    Returns:
        A Django response object
    """
    def __init__(self, content, mimetype='application/json', status=None, content_type='application/json'):
        super(JsonResponse, self).__init__(
            content=json.dumps(content),
            mimetype=mimetype,
            status=status,
            content_type=content_type)


def query(request, grid_id):
    """
    Returns the grid content in a JSON response

    query creates a new Grid instance based on the grid_id (which represents the Grid class), and calls
    grid.get_json_data to perform the actual query.

    Args:
        request: Django request
        grid_id: ID of the grid. The ID is generated by Grid.get_grid_id

    Returns:
        The JSON serialized grid contents.
    """
    cls = get_grid_class(grid_id)
    grid = cls()
    data = grid.get_json_data(request.GET)
    return JsonResponse(data)
