#coding=utf-8

"""JSON helper functions"""
import traceback
import sys
import thread

from django.conf import settings
from django.http import JsonResponse as DJR

from exceptionhandler import post_traceback

def JsonResponse(data=None):
    ret = {
        'code': 0,
        'data': data,
    }
    return DJR(ret, safe=False)

def JsonError(error_string):
    if not 'dev' in settings.LICENSE_KEY:
        exc_type, exc_value, exc_traceback_obj = sys.exc_info()
        if exc_type and exc_type.__name__ != 'ValueError':
            trace = traceback.format_exc()
            try:
                thread.start_new_thread(post_traceback, (exc_value, trace,))
            except:
                print "Error: unable to start report exception thread"
            #print '******', exc_type.__name__, type(exc_type.__name__)

    data = {
        'code': 1,
        'msg': error_string
    }
    return DJR(data, safe=False, json_dumps_params={'ensure_ascii':False})

def ForbiddenResponse():
    data = {
        'code': 1001,
        'msg': u'拒绝访问',
    }
    return DJR(data, safe=False)

def DataGridResponse(data, total, more=None):
    result = {
        'code': 0,
        'count':total,
        'data': data
    }
    if more:
        result['more'] = more
    return DJR(result, safe=False)

def EasyuiDataGridResponse(data, total):
    result = {
        'total':total,
        'rows': data,
    }
    return DJR(result, safe=False)

# For backwards compatability purposes
JSONResponse = JsonResponse
JSONError = JsonError
DataGridJSONResponse = DataGridResponse
ForbiddenJSONResponse = ForbiddenResponse
