#!/usr/bin/env python
# coding:utf-8 
import time
import json
from hashlib import md5
from toughlib import utils


def make_sign(secret, params=[]):
    """
        >>> make_sign("123456",[1,'2',u'中文'])
        '33C9065427EECA3490C5642C99165145'
    """
    _params = [utils.safeunicode(p) for p in params if p is not None]
    _params.sort()
    _params.insert(0, secret)
    strs = ''.join(_params)
    mds = md5(strs.encode('utf-8')).hexdigest()
    return mds.upper()


def check_sign(secret, msg):
    """
        >>> check_sign("123456",dict(code=1,s='2',msg=u'中文',sign='33C9065427EECA3490C5642C99165145'))
        True

    """
    if "sign" not in msg:
        return False
    sign = msg['sign']
    params = [utils.safestr(msg[k]) for k in msg if k != 'sign']
    local_sign = make_sign(secret, params)
    return sign == local_sign

def make_request(secret, **params):
    """
        >>> json.loads(make_request("123456",**dict(code=1,msg=u"中文",nonce=1451122677)))['sign']
        u'58BAF40309BC1DC51D2E2DC43ECCC1A1'
    """
    if 'nonce' not in params:
        params['nonce' ] = str(int(time.time()))
    params['sign'] = make_sign(secret, params.values())
    return json.dumps(params, ensure_ascii=False)

def make_response(secret, **result):
    """
        >>> json.loads(make_response("123456",**dict(msg=u"中文",nonce=1451122677)))['sign']
        u'E0D678176B757385879E4472063B5133'
        >>> make_response("123456",**dict(msg="helllo",nonce=1451122677))
        '{"nonce": 1451122677, "msg": "helllo", "code": 0, "sign": "DB30F4D1112C20DFA736F65458F89C64"}'
    """
    if 'code' not in result:
        result["code"] = 0
    if 'nonce' not in result:
        result['nonce' ] = str(int(time.time()))
    result['sign'] = make_sign(secret, result.values())
    return json.dumps(result, ensure_ascii=False)


def parse_request(secret, reqbody):
    """
        >>> parse_request("123456",'{"nonce": 1451122677, "msg": "helllo", "code": 0, "sign": "DB30F4D1112C20DFA736F65458F89C64"}')
        {u'nonce': 1451122677, u'msg': u'helllo', u'code': 0, u'sign': u'DB30F4D1112C20DFA736F65458F89C64'}
    """
    try:
        req_msg = json.loads(reqbody)
    except Exception as err:
        raise ValueError(u"parse params error")

    if not check_sign(secret, req_msg):
        raise ValueError(u"message sign error")

    return req_msg

if __name__ == "__main__":
    import doctest
    doctest.testmod()

    
@@ -846,23 +846,23 @@
 ef make_
-request
+message
 (secret,
@@ -1157,32 +1157,32 @@
 arams.values())%0A
+
     return json.
@@ -1220,616 +1220,8 @@
 e)%0A%0A
-def make_response(secret, **result):%0A    %22%22%22%0A        %3E%3E%3E json.loads(make_response(%22123456%22,**dict(msg=u%22%E4%B8%AD%E6%96%87%22,nonce=1451122677)))%5B'sign'%5D%0A        u'E0D678176B757385879E4472063B5133'%0A        %3E%3E%3E make_response(%22123456%22,**dict(msg=%22helllo%22,nonce=1451122677))%0A        '%7B%22nonce%22: 1451122677, %22msg%22: %22helllo%22, %22code%22: 0, %22sign%22: %22DB30F4D1112C20DFA736F65458F89C64%22%7D'%0A    %22%22%22%0A    if 'code' not in result:%0A        result%5B%22code%22%5D = 0%0A    if 'nonce' not in result:%0A        result%5B'nonce' %5D = str(int(time.time()))%0A    result%5B'sign'%5D = make_sign(secret, result.values())%0A    return json.dumps(result, ensure_ascii=False)%0A%0A
 %0Adef

make message