# -*- coding: utf-8 -*-
"""
Autores: Jorge García Ferreiro, Tomasso Innoccenti and Luis
Grupo 12

Este código es fruto ÚNICAMENTE del trabajo de sus miembros. Declaramos no haber
colaborado de ninguna manera con otros grupos, haber compartido el ćodigo con
otros ni haberlo obtenido de una fuente externa.
"""

dbName = 'giw';

from bottle import post, get, request, route, run, template, static_file
import pymongo
from pymongo import MongoClient # install MongoClient
from pymongo import ReturnDocument
import json

client 	= MongoClient()
db 		= client['giw']
users 	= db['users']

#####################################
########## ASSETS ROUTING ###########
#####################################

@route('/views/<filepath:path>')
def file_stac(filepath):
    return static_file(filepath, root="./views")

@route('/<filename:re:.*\.js>')
def javascripts(filename):
    return static_file(filename, root='static/')

@route('/<filename:re:.*\.css>')
def stylesheets(filename):
    return static_file(filename, root='static/')

@route('/<filename:re:.*\.(jpg|png|gif|ico)>')
def images(filename):
    return static_file(filename, root='static/')

@route('/<filename:re:.*\.(eot|ttf|woff|svg)>')
def fonts(filename):
    return static_file(filename, root='static/')

# ¡MUY IMPORTANTE!
# Todas las inserciones se deben realizar en la colección 'users' dentro de la
# base de datos 'giw'.

@get('/')
def registerUser():
	return template('register_user');


####################################
########### GET METHODS ############
####################################

# Display user profile.
@get('/<userID>')
def registerUser(userID):
	cursor = db.users.find({
		'_id' : userID
	});

	if (cursor.count() > 0): 
		user = cursor[0]
		return template('profile', user=user);
	
	return template('result', message="User doesn't exist...");

@get('/<userID>/edit')
def editUser_info_view(userID):
	
	cursor = db.users.find({
		'_id' : userID
	});

	if (cursor.count() == 0):
		print "No user with that ID"
		return "No user with that ID"
	else:
		user = cursor[0] # python dictionary from a user
		return template('change_email', user=user);

#####################################
########### POST METHODS ############
#####################################

''' 
	Insert a new user into our database
	Only if user doesn't exist on our system.
	When success, print a message and show
	a success view.
'''

@post('/add_user')
def add_user_post():
	
	message = {
		"success" : "[ Good ] The user was created :-)",
		"error" : "[ Error ] Your user exists on our database"
	}

	try:
		userID = str(request.forms.get('_id'));
		users.insert({
			'_id' : str(request.forms.get('_id')),
			'country': str(request.forms.get('country')),
			'zip': str(request.forms.get('zip')),
			'email': str(request.forms.get('email')),
			'gender': str(request.forms.get('gender')),
			'likes': str(request.forms.get('likes')).split(','), # Create array of strings.
			'password': str(request.forms.get('password')), 
			'year': str(request.forms.get('year'))
		});

	except pymongo.errors.DuplicateKeyError, e:
		if (pymongo.errors.DuplicateKeyError):
			print  "\n" + str(message['error']) + "\n" # display on console success
		return template('result', message=message['error'])

	print  "\n" + str(message['success']) + "\n" # display on console success
	return template('result', message=message['success'])

@post('/change_email')
def change_email():

	_id 	= request.forms.get('_id')
	email 	= str(request.forms.get('email'))

	try:
		updatedUser = users.find_one_and_update(
			{'_id':_id},
			{'$set' : {'email':email}},
			return_document=ReturnDocument.AFTER
		);
		return template('profile', user=updatedUser);
	except ValueError:
		print "Email coudln't change"
		print ValueError

	# User exists already on the database. 
	return template('result', message="[ BAD ] Your user exists on our database")

@post('/insert_or_update')
def insert_or_update():
    pass


@post('/delete')
def delete_id():

	_id = str(request.forms.get('_id'));

	deleted = users.find_one_and_delete({'_id': _id});
	
	if deleted != None:
		return template('result', message="User deleted successfully!");
	
	return template('result', message="User doesn't exist!");

@post('/delete_year')
def delete_year():
    pass

@route('/*')
def error():
	return "Not found"

run(host='127.0.0.1', port=3000);


@@ -3377,16 +3377,186 @@
 ess'%5D)%0A%0A
+'''%0A%09Change email of a user that already exists in the collection.%0A%09Como resultado de esta petici%C3%B3n el servidor web debe mostrar el n%C3%BAmero de documentos modificados.%0A'''%0A
 @post('/
@@ -3599,16 +3599,20 @@
 %09_id %09= 
+str(
 request.
@@ -3627,16 +3627,17 @@
 t('_id')
+)
 %0A%09email 
@@ -3672,16 +3672,38 @@
 ail'))%0A%0A
+%09updatedUser = None;%0A%0A
 %09try:%0A%09%09
@@ -3839,55 +3839,8 @@
 %09);%0A
-%09%09return template('profile', user=updatedUser);
 %0A%09ex
@@ -3893,68 +3893,8 @@
 e%22%0A%09
-%09print ValueError%0A%0A%09# User exists already on the database. %0A
 %09ret
@@ -3969,16 +3969,162 @@
 base%22)%0A%0A
+%09if (updatedUser == None):%0A%09%09print %220 documents modified%22%0A%09else:%0A%09%09print %221 documents modified%22%0A%09%0A%09return template('profile', user=updatedUser);%0A%0A
 @post('/

Change email post method