# coding: utf-8


from lib.Api import Mp, MpRe
from datetime import datetime
from Message import MsgText, MsgEvent
import cmd
from toolkit import url, BisReqHandler, Session

_token = 'weixinlx'

@url(r'/mp/dev')
class Dev(BisReqHandler):
    def get(self):
        self.render('mp/dev', title=u"微信订阅号测试")


@url(r'/mp/api')
class MpApi(BisReqHandler):
    def get(self):
        import hashlib
        al = [_token, self.get_argument('timestamp'), self.get_argument('nonce')]
        al.sort()

        if hashlib.sha1(''.join(al)).hexdigest() == self.get_argument('signature'):
            self.write(self.get_argument('echostr'))
        else:
            self.write('0000')


    def post(self):

        msg = reqMsg(self.request.body)

        if not msg:
            self.render_dict(code=46, msg='reqMsg')
            return

        res_msg = cmd.run(msg)

        if res_msg and res_msg.msgtype == 'text':
            self.render('mp/msgText', msg=res_msg)
        else:
            self.render_dict(code=53, msg='res_msg')

        sss = Session()
        sss.add(MpRe(xml=xml))
        sss.commit()

        self.write(res_msg or "@error")


def reqMsg(body):
    from BeautifulSoup import BeautifulSoup as Soup
    sp = Soup(body)

    fix = lambda node: node.string[:]


    sss = Session()
    sss.add(Mp(xml=str(sp)))
    sss.commit()

    par_b = {
        'tousername': fix(sp.tousername),
        'fromusername': fix(sp.fromusername),
        'createtime': int(fix(sp.createtime))
    }


    mtype = sp.msgtype.string

    if mtype == 'text':
        msg = MsgText(**par_b)
        msg.msgid = int(fix(sp.msgid))
        msg.content = fix(sp.content).lstrip()
        return msg

    if mtype == 'event':
        msg = MsgEvent(**par_b)
        msg.event = fix(sp.event)
        msg.eventkey = fix(sp.eventkey)
        return msg





