 
 # Exception handling
 app.use (error, request, response, next) ->
+	#if request.uonline.tx?.state() isnt 'closed'
+	request.uonline.tx?.rollback()
 	code = 500
 	if error.message is '404'
 		code = 404

app.post '/action/register',
	mustNotBeAuthed,
	setInstance('register'),
	(request, response) ->
		usernameIsValid = lib.validation.usernameIsValid(request.body.username)
		passwordIsValid = lib.validation.passwordIsValid(request.body.password)
		userExists = lib.user.userExists.sync(null, dbConnection, request.body.username)
		if (usernameIsValid is true) and (passwordIsValid is true) and (userExists is false)
			result = lib.user.registerUser.sync(
				null
				dbConnection
				request.body.username
				request.body.password
				'user'
			)
			response.cookie 'sessid', result.sessid
			response.redirect 303, '/'
		else
			options = request.uonline
			options.error = true


app.post '/action/go',
	mustBeAuthed,
	openTransaction,
	(request, response, next) ->
		result = lib.game.changeLocation.sync null, request.uonline.tx, request.uonline.user.character_id, request.body.to
		if result.result != 'ok'
			console.error "Location change failed: #{result.reason}"
		next()
	,
	commit,
	redirect(303, '/game/')


app.post '/action/attack',
	mustBeAuthed,
	openTransaction,
	(request, response, next) ->
		lib.game.goAttack.sync null, request.uonline.tx, request.uonline.user.character_id
		next()
	,
	commit,
	redirect(303, '/game/')


app.post '/action/escape',
	mustBeAuthed,
	openTransaction,
	(request, response, next) ->
		lib.game.goEscape.sync null, request.uonline.tx, request.uonline.user.character_id
		next()
	,
	commit,
	redirect(303, '/game/')


app.post '/action/hit',
	mustBeAuthed,
	openTransaction,
	(request, response, next) ->
		lib.game.hitOpponent.sync(
			null, request.uonline.tx,
			request.uonline.user.character_id,
			request.body.id,
			request.body.with_item_id
		)
		next()
	,
	commit,
	redirect(303, '/game/')


