# coding=utf-8
from __future__ import unicode_literals, absolute_import

import functools
import hashlib
import json

from django.conf import settings

from .api_control import ListInterfaceDescriptor
from .cache import page_cache
from .instance import api_manager


def _bind_general(name, **options):
    def binder(api_handler):
        return api_manager.bind_general(name=name, options=options, handler=api_handler)
    return binder


bind = functools.partial(_bind_general, with_context=False)
bind_context = functools.partial(_bind_general, with_context=True)
bind_context_raw = functools.partial(bind_context, return_data_only=False)


def cache_page(timeout):

    def wrap(f):

        # bind_context和cache_page装饰器一起使用,由于ctx参数问题会报错
        @functools.wraps(f)
        def decorated(**kwargs):
            method_url = "%s.%s?%s" % (f.__module__, f.__name__, json.dumps(kwargs, sort_keys=True))
            method_md5 = hashlib.md5(method_url).hexdigest()
            cache_key = "cache:%s:rpc:%s" % (method_md5, settings.VERSION)
            data = page_cache.get(cache_key)
            try:
                if data:
                    resp = json.loads(data)
                    return resp
            except:
                pass
            obj = f(**kwargs)
            page_cache.setex(cache_key, timeout, json.dumps(obj))
            return obj
        return decorated

    return wrap


list_interface = ListInterfaceDescriptor.decorator

