const mongo = require('../db')
const utils = require('../utils')

/**
 * User :: {
 *    id: String,
 *    username: String,
 *    password: String,
 *    createdAt: String
 * }
 */

/** String -> String -> User */
function createUser(username, password) {
    return {
        "id": utils.UUID(),
        "username": username,
        "password": utils.hashPassword(password),
        "createdAt": Date.now()
    }
}

/** String -> Promise(User, Error) */
function findUserByName(username) {
    return mongo.connect()
        .then(db => db.collection('users')
              .findOne({ username })
              .then(mongo.close(db)))
}

/** String -> Promise(Boolean, Error) */
function userExist(username) {
    return findUserByName(username)
        .then(user => user != null)
}

/** User -> Promise(User, Error) */
function saveUser(user) {
    return mongo.connect()
        .then(db => db.collection('users').insertOne(user)
        .then(mongo.close(db)))
        .then(() => user)
}

/** String -> String -> Promise({id, username, token : String}, Error) */
exports.register = function register(username, password) {
    return userExist(username)
        .then(exist => exist ?
                Promise.reject("The user already exist") :
                Promise.resolve(createUser(username, password)))
        .then(saveUser)
}

@@ -630,24 +630,594 @@
 se(db)))%0A%7D%0A%0A
+/** String -%3E String -%3E Promise((), Error) */%0Afunction ensureParams (username, password) %7B%0A    if (!/%5E%5B%5Cw-%5D%7B4,%7D$/.test(username)) %7B%0A        return Promise.reject(%22Invalid username%22)%0A    %7D%0A%0A    // https://github.com/mathiasbynens/regenerate%0A    // Allow any string that is at least 4-length long with any unicode char%0A    if (!/(%5B%5C0-%5CuD7FF%5CuE000-%5CuFFFF%5D%7C%5B%5CuD800-%5CuDBFF%5D%5B%5CuDC00-%5CuDFFF%5D%7C%5B%5CuD800-%5CuDBFF%5D(?!%5B%5CuDC00-%5CuDFFF%5D)%7C(?:%5B%5E%5CuD800-%5CuDBFF%5D%7C%5E)%5B%5CuDC00-%5CuDFFF%5D)%7B4,%7D/.test(password)) %7B%0A        return Promise.reject(%22Invalid password%22)%0A    %7D%0A%0A    return Promise.resolve()%0A%7D%0A%0A
 /** String -
@@ -1255,32 +1255,33 @@
 nction userExist
+s
 (username) %7B%0A   
@@ -1704,16 +1704,69 @@
   return
+ ensureParams(username, password)%0A        .then(() =%3E
  userExi
@@ -1767,16 +1767,17 @@
 serExist
+s
 (usernam
@@ -1770,32 +1770,33 @@
 Exists(username)
+)
 %0A        .then(e
@@ -1811,20 +1811,16 @@
 exist ?%0A
-    
         
@@ -1866,20 +1866,16 @@
 ist%22) :%0A
-    
         

Make test okay