import bcrypt
from psql import query, query_no_fetch, make_safe


#needed to hash the password (makes it more secure)
salt = bcrypt.gensalt()


def register_user(uname, psword, name, street, postal, city, country):
    """
    Input: Strings (Username, Password, Name, Street, Postal, City, Country)
    Checks whether a username already exists and if the user filled out all fields
    and that the postcode is a number. Then it hashes the password and stores all
    the data in the psql table 'users'
    Output: String that indicates the success of this function
    """
    #counts the given username, returns false if it counted >0
    res = query("SELECT COUNT(*) FROM users WHERE username='{}'".format(make_safe(uname)))
    if res[0][0] > 0:
        return "already_exists"
    try:
        postal = int(postal)
    except:
        pass
    #checks if all boxes were filled out and postcode is an integer
    if uname == "" or psword == "" or name == "" or street == "" or postal == "" or city == "" or country == "" or not isinstance(postal, int):
        return "fill_out_all"
    #hashes the password so it is not clear in our database
    hashed_password = bcrypt.hashpw(psword.encode('utf-8'), salt).decode('utf-8')
    #inserts the new user into the table
    query_no_fetch("INSERT INTO users VALUES ('{}', '{}', '{}', '{}', '{}', '{}', '{}')".format(make_safe(uname),
                                                                                                make_safe(hashed_password),
                                                                                                make_safe(name),
                                                                                                make_safe(street),
                                                                                                postal,
                                                                                                make_safe(city),
                                                                                                make_safe(country)))
    return "user_registered"


def is_login_successful(uname, psword):
    """
    Input: Strings(Username, Password)
    Checks if the given password matches the password in the table.
    Output: String that indicates the success of this function
    """
    #query to get the data corresponding to the given username
    res = query("SELECT * FROM users WHERE username='{}'".format(make_safe(uname)))
    #if the username doesn't exist
    if len(res) == 0:
        return "username_not_found", uname
    #if the correct password was entered
    if bcrypt.checkpw(psword.encode('utf-8'), res[0][1].encode('utf-8')):
        return "correct_password", uname
    #if none of the above worked
    return "wrong_password", uname
