// Sequelize is Promisified
// the 'then' method is called after all callbacks and events are processed succesfully
// the 'catch' method is called if an error occurs

// the code below is called from a context that has an Express request 'req' and
// requires callback 'done' to be called when done

User.findOne({ where: { localemail: email }})
    .then(function(existingUser) { // findOne succesful, zero or one records found

	// check to see if there's already a user with that email
	if (existingUser) 
	    return done(null, false, req.flash('loginMessage', 'That email is already taken.'));

    //  If we're logged in, we're connecting a new local account.
    if(req.user) {
    	// update user properties
        var user = req.user;
        user.localemail = email;
        user.localpassword = User.generateHash(password);
        user.save()
            .then (function() {
            	// user save succesful
                done(null, user);
            })
            .catch(function (err) {
            	// user save failed
                done(null, false, req.flash('loginMessage', err));});
            });
    } else {
        //  We're not logged in, so we're creating a brand new user.
        // create the user
        var newUser = User.build ({
            localemail: email, 
            localpassword: User.generateHash(password)
        });
        // store the newUser to the database
        newUser.save()
            .then(function() {
            	// newUser save succesful
                done (null, newUser);
            })
            .catch(function(err) {
            	// newUser save failed
                done(null, false, req.flash('loginMessage', err));});
            }
        })
	.catch(function (e) {
		// some error occurred while executing the findone query
		done(null, false, req.flash('loginMessage',e.name + " " + e.message));				
	})