import time
import random
import base64
import string
import traceback
from functools import wraps
from datetime import datetime
from django.core.files.base import ContentFile
from django.utils.encoding import smart_text
from core.utils import log as logger


def fn_timer(function):
    @wraps(function)
    def function_timer(*args, **kwargs):
        t0 = time.time()
        result = function(*args, **kwargs)
        t1 = time.time()
        print("Total time running %s: %s seconds" %
              (function.func_name, str(t1 - t0))
              )
        return result

    return function_timer


def catch(func):
    @wraps(func)
    def wrap(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            logger.error(traceback.format_exc())
            return None

    return wrap


def inner_result(func):
    @wraps(func)
    def wrap(*args, **kwargs):
        code = '0'
        msg = ''
        data = {}
        try:
            data = func(*args, **kwargs)
        except Exception as e:
            logger.error(traceback.format_exc())
            code = '-1'
            msg = smart_text(e) or '未知错误'
        return {'code': code, 'msg': msg, 'data': data}

    return wrap


def gen_random_str(chars=None, length=8):
    if not chars:
        chars = string.digits
    return ''.join([random.choice(chars) for i in range(length)])


def gen_key(length=32):
    chars = '1234567890abcdefghijklmnopqrstuvwxyz+=/*@='
    return gen_random_str(chars, length)


def gen_time_str(t=None, ext_chars=None, ext_length=0):
    if not t:
        t = datetime.now()
    if not ext_chars:
        ext_chars = string.digits
    time_str = t.strftime('%Y%m%d%H%M%S')
    return "{0}{1}".format(time_str, gen_random_str(ext_chars, ext_length))


def get_client_ip(request):
    if not request:
        return ''
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip


def get_webkit(request):
    user_agent = request.META.get('HTTP_USER_AGENT').lower()
    webkit = 0  # 普通浏览器
    if user_agent.find('micromessenger') > -1:  # 微信
        webkit = 1
    if user_agent.find('alipay') > -1:  # 支付宝
        webkit = 2
    return webkit


# def get_base64_image(base64data):
#     cur_time = str(time.time())
#     rand_num = str(random.randint(0, 1000))
#     files = {}
#     try:
#         img = base64data
#         if isinstance(img, basestring) and img.startswith('data:image'):
#             fm, img = img.split(';base64')
#             ext = fm.split('/')[-1]
#             image = ContentFile(base64.b64decode(img), name='pc' + cur_time + rand_num + '.' + ext)
#             files['image'] = image
#     except:
#         pass
#     return files


def dict_to_xml(obj_dict):
    keys = obj_dict.keys()
    keys.sort()
    data = '<xml>'
    for key in keys:
        data += '<%s>%s</%s>' % (key, obj_dict[key], key)
    data += '</xml>'
    return data
