<commit_before># -*- coding: utf-8 -*-
"""
Autores: <NAME>, <NAME> 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.
"""

"""
	IMPLICIT SCHEME

	+---------------------------------------------------+
	| key             | types  | occurrences | percents |
	| --------------- | ------ | ----------- | -------- |
	| _id             | String |        1000 |    100.0 |
	| address         | Object |        1000 |    100.0 |
	| address.country | String |        1000 |    100.0 |
	| address.zip     | Number |        1000 |    100.0 |
	| email           | String |        1000 |    100.0 |
	| gender          | String |        1000 |    100.0 |
	| likes           | Array  |        1000 |    100.0 |
	| password        | String |        <PASSWORD> |    100.0 |
	| year            | Number |        1000 |    100.0 |
	+---------------------------------------------------+

"""

from bottle import get, run, request, template

# Resto de importaciones
import pymongo
from pymongo import MongoClient # install MongoClient
from pymongo import ReturnDocument

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

@get('/find_user_id')
def find_user_id():
	# http://localhost:8080/find_user_id?_id=user_1
   
	maxParams   = 1 
	params      = dict((k,request.query.getall(k)) for k in request.query.keys())
	validParams = ['_id']

	(isValid, msg) = checkParameters(params, maxParams, validParams)

	if isValid:
		userID=params['_id'][0]
		cursor = db.users.find({'_id' : userID});
		if (cursor.count() == 0):
			msg = "No user with that ID"
			return template('error', msg=msg)
			#return template('error', msg=message)
		else:
			userList = []
			for c in cursor:
				userList.append(c)
	
			return str(userList)
			#return template('table', content=userList)
	else:
		return template('error', msg=msg)


''' 
	Compose a query: returns array of Dictionaries
	where each element is each of the parameters we want to ask
	Structure: query = [ {"_id":_id},{"name":name}, ] 
'''

def composeQuery(params):

	query = [] # List of dictionaries (json objects)

	for key in params:
		elem  = {}
		value = params[key][0] # Params can have multiple values for each array element

		if key == 'year':
			value = int(value) # Cast to integer when year.

		elem[key] = value  # save value as dictionary
		query.append(elem) # push dictionary to query

	return query




# http://localhost:8080/find_users?gender=Male
# http://localhost:8080/find_users?gender=Male&year=2009

''' 
This method can be used for find_users_or or find_users
the only that changes is that when you pass filter_and as true
the program will make an and of all the paramters 
and when or, it make an or on the query
'''

def filterUsers_and_or(filter_and):

	URL_Params 	= dict((k,request.query.getall(k)) for k in request.query.keys())
	maxParams 	= 4
	validParams = ['_id', 'email', 'gender', 'year']

	(valid, msg)= checkParameters(URL_Params, maxParams, validParams) # Check if URL_ parameters are correct. Returning true/false and a message

	if valid:

		query  = composeQuery(URL_Params)

		if filter_and:
			print "Make an and"
			cursor = db.users.find({"$and":query});
		else:
			cursor = db.users.find({"$or":query});

		numResults = cursor.count()
		print "Make an and"

		if numResults <= 0:
			return template('error', msg='We didn\'t find any user with that information')
		else:
			userList = [] # We found some users. Compose a list of users

			for user in cursor:
				userList.append(user)

			return template('table', userList=userList, totalResults=numResults);
	else:
		return template('error', msg=msg)

@get('/find_users')
def find_users():
	filter_and = True; # make and with all parameters
	return filterUsers_and_or(filter_and);

@get('/find_users_or')
def find_users_or():
	filter_and = False; # make and with all parameters
	return filterUsers_and_or(filter_and);

# http://localhost:8080/find_users_or?gender=Male&year=2000

@get('/find_users_or2')
def find_users_or2():

	URL_Params 	= dict((k,request.query.getall(k)) for k in request.query.keys())
	maxParams 	= 4
	validParams = ['_id', 'email', 'gender', 'year']

	(valid, msg)= checkParameters(URL_Params, maxParams, validParams) # Check if URL_ parameters are correct. Returning true/false and a message

	if valid:

		query  = composeQuery(URL_Params)
		cursor = db.users.find({"$or":query});
		numResults = cursor.count()

		if numResults <= 0:
			return template('error', msg='We didn\'t find any user with that information')
		else:
			userList = [] # We found some users. Compose a list of users

			for user in cursor:
				userList.append(user)

			return template('table', userList=userList, totalResults=numResults);
	else:
		return template('error', msg=msg)

	   
@get('/find_like')
def find_like():
	# http://localhost:8080/find_like?like=football
	
	maxParams   = 1 
	params      = dict((k,request.query.getall(k)) for k in request.query.keys())
	validParams = ['like']

	(isValid, msg) = checkParameters(params, maxParams, validParams)

	if isValid:
		like = params['like']
		cursor = db.users.find({ 'likes': { '$in' : like }} );
		if (cursor.count() == 0):
			return template('error', msg="No user with that like")
		else:
			userList = []
			for c in cursor:
				userList.append(c)
	
			return template('table', userList=userList)
	else:
		return template('error', msg=msg)


@get('/find_country')
def find_country():
	# http://localhost:8080/find_country?country=Spain
	maxParams   = 1 
	params      = dict((k,request.query.getall(k)) for k in request.query.keys())<commit_msg>Refactored to filterUsers_and_or()<commit_after># -*- coding: utf-8 -*-
"""
Autores: <NAME>, <NAME> 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.
"""

"""
	IMPLICIT SCHEME

	+---------------------------------------------------+
	| key             | types  | occurrences | percents |
	| --------------- | ------ | ----------- | -------- |
	| _id             | String |        1000 |    100.0 |
	| address         | Object |        1000 |    100.0 |
	| address.country | String |        1000 |    100.0 |
	| address.zip     | Number |        1000 |    100.0 |
	| email           | String |        1000 |    100.0 |
	| gender          | String |        1000 |    100.0 |
	| likes           | Array  |        1000 |    100.0 |
	| password        | String |        <PASSWORD> |    <PASSWORD> |
	| year            | Number |        1000 |    100.0 |
	+---------------------------------------------------+

"""

from bottle import get, run, request, template

# Resto de importaciones
import pymongo
from pymongo import MongoClient # install MongoClient
from pymongo import ReturnDocument

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

@get('/find_user_id')
def find_user_id():
	# http://localhost:8080/find_user_id?_id=user_1
   
	maxParams   = 1 
	params      = dict((k,request.query.getall(k)) for k in request.query.keys())
	validParams = ['_id']

	(isValid, msg) = checkParameters(params, maxParams, validParams)

	if isValid:
		userID=params['_id'][0]
		cursor = db.users.find({'_id' : userID});
		if (cursor.count() == 0):
			msg = "No user with that ID"
			return template('error', msg=msg)
			#return template('error', msg=message)
		else:
			userList = []
			for c in cursor:
				userList.append(c)
	
			return str(userList)
			#return template('table', content=userList)
	else:
		return template('error', msg=msg)


''' 
	Compose a query: returns array of Dictionaries
	where each element is each of the parameters we want to ask
	Structure: query = [ {"_id":_id},{"name":name}, ] 
'''

def composeQuery(params):

	query = [] # List of dictionaries (json objects)

	for key in params:
		elem  = {}
		value = params[key][0] # Params can have multiple values for each array element

		if key == 'year':
			value = int(value) # Cast to integer when year.

		elem[key] = value  # save value as dictionary
		query.append(elem) # push dictionary to query

	return query

''' 
This method can be used for find_users_or or find_users
the only that changes is that when you pass filter_and as true
the program will make an and of all the paramters 
and when or, it make an or on the query
'''

def filterUsers_and_or(make_and):

	URL_Params 	= dict((k,request.query.getall(k)) for k in request.query.keys())
	maxParams 	= 4
	validParams = ['_id', 'email', 'gender', 'year']

	(valid, msg)= checkParameters(URL_Params, maxParams, validParams) # Check if URL_ parameters are correct. Returning true/false and a message

	if valid:

		query  = composeQuery(URL_Params)

		if make_and:
			cursor = db.users.find({"$and":query});
		else:
			cursor = db.users.find({"$or":query});

		numResults = cursor.count()

		if numResults <= 0:
			return template('error', msg='We didn\'t find any user with that information')
		else:
			userList = [] # We found some users. Compose a list of users

			for user in cursor:
				userList.append(user)

			return template('table', userList=userList, totalResults=numResults);
	else:
		return template('error', msg=msg)

# http://localhost:8080/find_users?gender=Male
# http://localhost:8080/find_users?gender=Male&year=2009

@get('/find_users')
def find_users():
	filter_and = True; # make and with all parameters
	return filterUsers_and_or(filter_and);

# http://localhost:8080/find_users_or?gender=Male&year=2000

@get('/find_users_or')
def find_users_or():
	filter_and = False; # make and with all parameters
	return filterUsers_and_or(filter_and);

@get('/find_like')
def find_like():
	# http://localhost:8080/find_like?like=football
	
	maxParams   = 1 
	params      = dict((k,request.query.getall(k)) for k in request.query.keys())
	validParams = ['like']

	(isValid, msg) = checkParameters(params, maxParams, validParams)

	if isValid:
		like = params['like']
		cursor = db.users.find({ 'likes': { '$in' : like }} );
		if (cursor.count() == 0):
			return template('error', msg="No user with that like")
		else:
			userList = []
			for c in cursor:
				userList.append(c)
	
			return template('table', userList=userList)
	else:
		return template('error', msg=msg)


@get('/find_country')
def find_country():
	# http://localhost:8080/find_country?country=Spain
	maxParams   = 1 
	params      = dict((k,request.query.getall(k)) for k in request.query.keys())
{'fraction_non_alphanumeric': 0.15283429544809313, 'fraction_numerical': 0.021387337938866283, 'mean_word_length': 3.047491382612026, 'pattern_counts': {'":': 9, '<': 13, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5075550', 'n_tokens_mistral': 3768, 'n_tokens_neox': 3372, 'n_words': 984}