import json

from django.views.decorators.csrf import csrf_exempt

from models import BaseDataSource
from passerelle.utils import to_json


def get_data(request, slug, id=None):
    ds = BaseDataSource.objects.get_slug(slug, request)
    kwargs = {}
    for param in (ds.parameters or ()):
        kwargs[param] = request.GET.get(param)
    if id is not None:
        return ds.get_data_by_id(id, **kwargs)
    if ds.parameters and 'q' in ds.parameters:
        return ds.get_data(**kwargs)
    q = request.GET.get('q')
    if q:
        q = q.lower()
        return [x for x in ds.get_data(**kwargs) if q in x['text'].lower()]
    else:
        return ds.get_data(**kwargs)

def post_data(request, slug, id=None):
    ds = BaseDataSource.objects.get_slug(slug, request)
    data = json.loads(request.raw_post_data)
    if id is not None:
        return ds.post_data_by_id(id, data)
    kwargs = {}
    for param in (ds.parameters or ()):
        kwargs[param] = request.GET.get(param)
    return ds.post_data(data, **kwargs)

@csrf_exempt
@to_json('api')
def json_view(request, slug, id=None, **kwargs):
    if request.method == 'GET':
        return get_data(request, slug, id=id)
    if request.method == 'POST':
        return post_data(request, slug, id=id)

@to_json('api')
def jsonp(request, slug, **kwargs):
    request.GET = request.GET.copy()
    request.GET['format'] = 'jsonp'
    return get_data(request, slug)
