from db.user import User
from app import app
from middlewares.auth import login_required
from flask import jsonify
import hashlib
from utils.jwt import generate_jwt
from flask import g, request


@app.route('/')
@login_required
def hello_world():
    print(g.user.get_id())
    return jsonify({"message": "OK"})


@app.route('/signup', methods=["POST"])
def signup():
    body = request.json
    hashed_password = hashlib.md5(body["password"].encode()).hexdigest()
    u = User(
        first_name=body["first_name"],
        last_name=body["last_name"],
        email=body["email"],
        hashed_password=hashed_password)
    u.store()
    return jsonify({"token": generate_jwt(u.get_id()), "type": "Bearer"})


@app.route('/login', methods=["POST"])
def login():
    body = request.json
    email = body["email"]
    password = body["password"]
    u = User.find_by_username(email=email)
    if u.compare_password(password):
        return jsonify({"token": generate_jwt(u.get_id()), "type": "Bearer"})
    return jsonify({"Error": "Email or password is not matched"}), 401
