"""Routes for register."""
import os, json, security, utils
from bottle import Bottle, route, view, post, request, redirect, abort

register = Bottle()

@register.route("/register")
@view("register")
@security.require_admin
def register_user():
    """Presents user with form to register a new user."""
    path = os.path.join("db", "surveys") # Make sure surveys/ or create it otherwise
    os.makedirs(path, exist_ok=True)
    surveys = next(os.walk(path))[1]

    return dict(
        surveys = surveys,
    )

@register.post("/register")
@view("register")
@security.require_admin
def register_user():
    """Validate and append new user to users.json."""
    path = os.path.join("db", "users.json")
    users = utils.safejsonload(path)

    username = request.forms.get("user")
    password = request.forms.get("password")

    # Register by writing into users.json with hashed password and salt
    if "/" not in username and username not in users and password.isprintable():
        salt, pw_hash = security.hash_password(password)
        users[username] = dict(
            hash = pw_hash.hex(),
            salt = salt.hex(),
            admin = False,
            surveys = request.forms.getall("surveys"),
        )
        utils.safejsondump(users, path)

        redirect("/users")

    # Respond 400 on invalid username (contains / or already exists) or password
    else:
        abort(400)
