from flask import Flask,redirect,render_template,request
import operatefile
import hashlib

app = Flask(__name__)

operatefile.read_file()
def md5(string):
    return hashlib.md5(string).hexdigest()

@app.route('/')
def index():
    return render_template('login.html')

@app.route('/login',methods=['POST'])
def login():

    user = request.form.get('user')
    pwd = request.form.get('pwd')

    if user in operatefile.user_dict and md5(pwd) == operatefile.user_dict.get(user)[-1]:

        return redirect('/userlist')
    else:
        return render_template('login.html')

@app.route('/userlist')
def userlist():
    return render_template('userlist.html',ulist=operatefile.user_dict.items())

@app.route('/adduser',methods=['POST'])
def adduser():

    user_list = []
    line = {key:request.form.get(key) for key in request.form if key != 'add'}

    user_list.append(('%s,%s,%s,%s,%s,%s')%(line.get('user'),line.get('age'),line.get('class'),line.get('phone_num'),line.get('address'),md5(line.get('password'))))

    if line.get('user') not in operatefile.user_dict:
        operatefile.append_file(user_list[0])
        operatefile.read_file()
        return redirect('/userlist')
    else:
        return redirect('/userlist')


@app.route('/del')
def deluser():

    user_str = ""
    user = request.args.get('user')

    res = 'name,age,class,phone_num,address,password'
    if user in operatefile.user_dict:

        operatefile.user_dict.pop(user)

        for i in operatefile.user_dict.items():
            user_str += i[0] +',' + ','.join(i[1]) + '\n'

        user_str = res + '\n' + user_str

        operatefile.write_file(user_str)
        operatefile.read_file()
        return redirect('/userlist')
    else:
        return redirect('/userlist')

@app.route('/update')
def update():
    user = request.args.get('user')
    line = operatefile.user_dict.get(user)
    return render_template('update.html',user=user,line=line)

@app.route('/updateuser',methods=['POST'])
def updateuser():

    user_list = []
    user_str = ""
    line = {key:request.form.get(key) for key in request.form if key != 'add'}
    user_list.append(('%s,%s,%s,%s,%s,%s')%(line.get('user'),line.get('age'),line.get('class'),line.get('phone_num'),line.get('address'),md5(line.get('password'))))
    res = 'name,age,class,phone_num,address,password'
    if line.get('user') in operatefile.user_dict:

        operatefile.user_dict.pop(line.get('user'))

        for i in operatefile.user_dict.items():
            user_str += i[0] + ',' + ','.join(i[1]) + '\n'

        user_str = res +'\n' + user_str + user_list[0]

        operatefile.write_file(user_str)
        operatefile.read_file()

        return redirect('/userlist')
    else:
        return redirect('/userlist')

if __name__ == '__main__':
    app.run(debug=True)