# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division
from angular_api.logic import APIException, get_object_or_404, user_passes_test
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.conf import settings
import simplejson as json
import traceback
import datetime
import inspect
import sys


#region api functions
def get_obama_years(**kwargs):
    return datetime.date.today().year - 1961


def yet_another_api_function(**kwargs):
    return get_object_or_404(User, id=200)  # error 404 test


@user_passes_test(lambda u: u.is_superuser)
def get_administrative(**kwargs):
    return 'Hello Administrator!'


#endregion


functions = dict(
    inspect.getmembers(
        sys.modules[__name__],
        lambda f: inspect.isfunction(f) and f.__module__ == __name__
    )
)

#functions['jasmine_tests_run_before'] = jasmine.jasmine_tests_run_before
#functions['jasmine_tests_run_after'] = jasmine.jasmine_tests_run_after


@login_required
def api_handler_global(request):
    if request.method != 'POST':
        raise APIException.forbidden()

    try:
        data = json.loads(request.body)
    except:
        data = dict(request.REQUEST)

    data['user'] = request.user
    response = {}
    status = 200

    try:
        function_result = functions[data['function']](**data)
        if function_result:
            response['result'] = function_result
    except APIException as e:
        response['error'] = e.message
        status = e.status
    except Exception as e:
        if settings.DEBUG:
            print(traceback.format_exc(), e)
        response['error'] = 'Server Error'
        status = 500

    return HttpResponse(json.dumps(response), content_type='application/json', status=status)

@@ -221,16 +221,70 @@
 equired%0A
+from django.views.decorators.http import require_POST%0A
 from dja
@@ -961,376 +961,107 @@
 %0A)%0A%0A
-#functions%5B'jasmine_tests_run_before'%5D = jasmine.jasmine_tests_run_before%0A#functions%5B'jasmine_tests_run_after'%5D = jasmine.jasmine_tests_run_after%0A%0A%0A@login_required%0Adef api_handler_global(request):%0A    if request.method != 'POST':%0A        raise APIException.forbidden()%0A%0A    try:%0A        data = json.loads(request.body)%0A    except:%0A        data = dict(request.REQUEST)%0A
+%0A@require_POST%0A@login_required%0Adef api_handler_global(request):%0A    data = json.loads(request.body)
 %0A   
@@ -1105,17 +1105,9 @@
 onse
- = %7B%7D%0A   
+,
  sta
@@ -1111,16 +1111,24 @@
 status =
+ dict(),
  200%0A%0A  
@@ -1328,16 +1328,24 @@
 'error'%5D
+, status
  = e.mes
@@ -1348,33 +1348,17 @@
 .message
-%0A        status =
+,
  e.statu
@@ -1483,16 +1483,24 @@
 'error'%5D
+, status
  = 'Serv
@@ -1512,25 +1512,9 @@
 ror'
-%0A        status =
+,
  500

upgrade api handler