from flask import Flask, request, make_response, jsonify, send_file, session
from core import zju
from wx import sign
from pool import pool

app = Flask(__name__)
sess_pool = pool()

def jsonres(res, status_code=200):
    response = make_response(jsonify(res), status_code)
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response

allow = []
with open('./allow.account', 'r') as f:
    allow = list(f.readlines())
allow = [i.strip('\n') for i in allow]

@app.route('/', methods=['GET'])
def hello():
    return 'xixi~'


@app.route('/signature', methods=['GET'])
def signature():
    url = request.args.get('url')
    try:
        obj = sign()
        res = {
            'code': 0,
            "signature": obj.get_signature(url=url)
        }
        del obj
        return jsonres(res)
    except Exception as e:
        res = {
            'code': 1,
        }
        print(e)
        return jsonres(res)

@app.route('/qrcode', methods=['GET'])
def qrcode():
    # no username nor password
    sess = zju()
    res = {}
    res['status'] = True
    res['msg'] = 'qrcode ok'
    res['src'], uuid = sess.get_qrcode()
    res['uuid'] = uuid
    del sess
    return jsonres(res)

@app.route('/qrpoll', methods=['GET'])
def qrpoll():
    res = {}
    sess = zju()
    uuid = str(request.args.get('uuid'))
   # if sess_pool.exists(sess_id):
   #     sess = sess_pool.get(sess_id)
   # else:
   #     res['status'] = False
   #     res['msg'] = 'uuid error'
   #     return jsonres(res)

    try:
        token = sess.get_qrcode_token(uuid)
        res['status'] = True
        res['msg'] = 'qrcode pass'
        res['token'] = token
        del sess
        return jsonres(res)
    except Exception:
        res['status'] = False
        res['msg'] = 'qrcode invalid'
        del sess
        return jsonres(res)


@app.route('/qrlogin', methods=['GET'])
def data():
    res = {}
    sess = zju()
    token = str(request.args.get('token'))

    try:
        sess.login_qrcode(token)
    except Exception:
        res['status'] = False
        res['msg'] = 'login error'
    
    try:
        sess.go(res)
        res['status'] = True
        res['msg'] = 'data ok'
        del sess
        return jsonres(res)
    except Exception:
        res['status'] = False
        res['msg'] = 'data error'
        del sess
        return jsonres(res)
    
    

@app.route('/login', methods=['POST'])
def login():
    res = {}
    username = request.form['username']
    password = request.form['password']

    #logger.info("func: login user: {}".format(username))

    if username not in allow:
        res['status'] = False
        res['msg'] = 'stuid error'
        return jsonres(res)


    sess = zju(username, password)


    try:
        status = sess.login()
    except Exception:
        res['status'] = False
        res['msg'] = 'login error'
        del sess
        return jsonres(res)

    res['status'] = status
    res['msg'] = 'login ok' if status else 'login fail'

    if not status:
        del sess
        return jsonres(res)
    else:
        try:
            sess.go(res)
            del sess
            return jsonres(res)
        except Exception as e:
            res['status'] = False
            res['msg'] = 'fetch error'
            del sess
            return jsonres(res)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=6000)
