# -*- coding:utf-8 -*-
# @Time    : 2020/5/18 9:56 上午
# @Author  : Creat by Han
from itertools import groupby
from django.shortcuts import render
import os
import sys 
import json
from collections import OrderedDict
from importlib import import_module
JsonResponse = lambda x: HttpResponse(json.dumps(x), content_type="application/javascript")
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
current_path = os.path.dirname(__file__)
_modules = os.listdir(os.path.dirname(__file__))
child_modules = [i for i in _modules if not i.endswith(".py") and (not i.endswith(".pyc")) and (not i.startswith("__"))]

for m in os.walk(current_path):
    if m[0] == current_path:
        continue
    module_name = m[0].split('/')[-1]
    if '\\' in m[0]:
        module_name = m[0].split('\\')[-1]
    if '__init__.py' not in m[2]:
        continue
    for i in [i.replace(".py", "") for i in m[2] if i.endswith(".py") and (not i.startswith("__"))]:
        import_module('smartfarming.api.views.%s.%s' % (module_name,i))

__all__ = [i.replace(".py", "") for i in _modules if i.endswith(".py") and (not i.startswith("__"))]
__all__ += ["api_gateway", "api_document"]


@csrf_exempt
def api_gateway(request):
    method = request.GET.get("method")
    a = {'method': method}
    _ = sys.api_config.get(method)
    if _:
        function = _
        if function:
            return function(request)
    result = JsonResponse({"errorCode": 404, "data": None, "message": "can not find the method!", "formError": {}})
    if "HTTP_ORIGIN" in request.META:
        result["Access-Control-Allow-Origin"] = request.META.get("HTTP_ORIGIN")
    return JsonResponse(a)

def api_document(request):
    if hasattr(sys, "api_config"):
        info = list(sys.api_config.items())
    else:
        info = []
    info.sort(key=lambda x: '.'.join(x[0].split(".")[:-1]))
    result = OrderedDict()
    for module_name, _iter in groupby(info, key=lambda x: ".".join(x[0].split(".")[:-1])):
        result[module_name] = []
        for j in _iter:
            result[module_name].append((j[0], j[1].__doc__ or '', j[1].login_required,
                                        j[1].inteam_required,
                                        j[1].inproject_required,
                                        j[1].api_factory))
    result = result.items()
    return render(request,"api_document.html",locals())