# encoding: utf-8

from apistar import Route, App
import redis
from redisConfig import redisConf,jsonList
from apistar import http
import pyodbc
import json
r = redis.StrictRedis(host=redisConf['host'], port=redisConf['port'])


"""
API 设计
========================================================
"""

# API 接收用户选股参数 post

def checkDict(mydict):
    mydict = (mydict)
    for key in mydict:
        print('mmm',mydict[key]['stockPicker']['pick'],type(mydict[key]['stockPicker']['pick']))
        #if mydict[key]['stockPicker']['pick'] == 'true'
        #if mydict[key]['criteriaDcit']
    return 
    
def strategy_params(request: http.Request)-> http.JSONResponse:
    """接收策略参数"""
    #print('-----------------------------------clientAPI------------------------------------------------')
    
    mydict = json.loads(str(request.body.decode('utf-8')))
    checkDict(mydict)
    r.lpush(jsonList, str(mydict)) # myJson is the type of str
    return str(mydict)


# API2 获取策略的运行结果 get
def strategy_results(strategyID):
    """返回策略运行结果"""
    DBcnxn = pyodbc.connect(DSN = 'TEST',autocommit=True)
    DBcursor = DBcnxn.cursor()
    items = 'oneDay,positionList,cash,positionListValue,totalValue,strategyID'
    DBcursor.execute('select %s from BTrecords items where strategyID = %s'%(items,strategyID))
    raw = DBcursor.fetchall()
    print(raw)
    return raw

routes = [
    Route('/p', "POST", strategy_params),
    Route('/g', "GET", strategy_results),
]

app = App(routes=routes)


if __name__ == "__main__":
    app.serve('0.0.0.0',8080,use_debugger=False)
