# coding=utf8
from __future__ import unicode_literals, absolute_import, print_function


from .context import ConnectionInfo


import six
import json
import traceback
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

from rpc.instance import api_manager
from rpc.context import Request
from rpc.tool.log_tool import _error_logger


def render_json(f):
    def decorated(request, *args, **kwargs):
        obj = f(request, *args, **kwargs)

        data = json.dumps(obj)
        response = HttpResponse(content=data, content_type='application/json')
        return response
    return decorated


@csrf_exempt
@render_json
def once(request):
    method = request.POST.get('method')
    params = request.POST.get('params')
    session_key = request.POST.get('session_key')
    environment = request.POST.get('environment')

    if method and params:
        params = json.loads(params)
    else:
        raise Exception("bad method or params")

    if environment:
        environment = json.loads(environment)
    else:
        environment = None

    conn_info = ConnectionInfo(request)
    return api_manager.dispatch(
        request=Request(
            method=method,
            params=params,
            session_key=session_key,
            environment=environment,
        ),
        connection_info=conn_info,
    )


@csrf_exempt
@render_json
def batch(request):
    requests_json = request.POST.get('requests')
    requests_raw = json.loads(requests_json)

    conn_info = ConnectionInfo(request)

    result_list = []
    for req in requests_raw:
        try:
            result = api_manager.dispatch(
                Request(
                    method=req.get('method'),
                    params=req.get('params'),
                    session_key=req.get('session_key'),
                    environment=req.get('environment'),
                ),
                connection_info=conn_info,
            )
        except Exception as e:
            _error_logger.exception(e)

            if settings.DEBUG:
                result = {
                    'debug': {
                        'exception': {
                            'message': six.text_type(e),
                            'traceback': traceback.format_exc(),
                        }
                    }
                }
            else:
                result = None
        result_list.append(result)

    return result_list


def index(request):
    return HttpResponse("gaia")

