/* Team-Sport */

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var request = require('request');
var Promise = require("bluebird");
var config = require('./config');
var hat = require('hat');

var User = mongoose.model("User", new Schema(config.schemas.user));
var Event = mongoose.model('Event', new Schema(config.schemas.event));

Promise.promisify(request);

mongoose.connect(config.database);

//Login
exports.login = function(username, password) {
	return User.findOne({
		name: username
	}).exec().then(function(user){
		if (!user)
			throw "Benutzer existiert nicht!"
		else if (user.password != password)
			throw "Falsches Passwort!"

		return Promise.resolve(user);
	});
};

//Registrieren
exports.register = function(username, password, email) {
	return User.findOne({
		name: username
	}).exec().then(function(user){
		if (user) {
			throw "Benutzer existiert bereits!"
		}

		return new User({
					name: username,
					password: password,
					email: email
		}).save().exec();
	});
};

exports.findEvent = function(){
  return Event.find().exec();
}

exports.addEvent = function(object, user) { //object is the
  var x = parseFloat(object.x);
  var y = parseFloat(object.y);

  var event = new Event({
    coordinates: [y, x],
    name: object.name, // ???
    type: object.type,
    description: object.description,
    start: new Date(object.start),
    end: new Date(object.end),
    people: [user.id]
  });

  return event.save().exec();
}

//id = event id
exports.enterEvent = function(id, user) { // adds your ID to the event people
  return Event.find({id}).exec()
  .then(function(event) {
    event.people.push(user.id);
    return event.save().exec();
  });
}

//Google Geocoding
exports.getCoordinates = function(location) {
  return request.getAsync(`https://maps.googleapis.com/maps/api/geocode/json?key=${config.maps}&address=${location}`)
  .then((response, _body) => {
    var body = JSON.parse(_body);
    //TODO: SECURITY WARNING - O(n^2) code.

    //Locality
    var candidates = [];

    if(body.status === 'ZERO_RESULTS' || body.status === 'OVER_QUERY_LIMIT')
      return Promise.resolve();

    if(body.status !== 'OK')
      throw body.error_message;

    body.results.forEach(function(result) {
      var componentIndex;
      var isLocality = result['address_components'].some(function(component, index) {
        return component.types.some(function(type) {
          if(type === 'locality') {
            componentIndex = index;
            return true;
          }

          return false;
        });
      });

      if(isLocality && result['address_components'][componentIndex] === 'Köln')
        candidates.push(result);
    });

    return Promise.resolve(candidates[0]);
  });
}

@@ -205,16 +205,48 @@
 ('hat');
+%0Avar crypto = require('crypto');
 %0A%0Avar Us
@@ -535,39 +535,32 @@
 e: username%0A%09%7D).
-exec().
 then(function(us
@@ -574,13 +574,21 @@
 if (
-!
 user
+ === null
 )%0A%09%09
@@ -650,16 +650,21 @@
 word != 
+hash(
 password
@@ -664,16 +664,17 @@
 assword)
+)
 %0A%09%09%09thro
@@ -858,15 +858,8 @@
 %09%7D).
-exec().
 then
@@ -883,17 +883,14 @@
 %09%09if
- 
 (user)
- %7B
 %0A%09%09%09
@@ -929,21 +929,22 @@
 s!%22%0A
-%09%09%7D%0A%0A%09%09return
+%0A%09  var user =
  new
@@ -951,18 +951,16 @@
  User(%7B%0A
-%09%09
 %09%09%09name:
@@ -973,18 +973,16 @@
 ame,%0A%09%09%09
-%09
-%09
 password
@@ -983,24 +983,29 @@
 ssword: 
+hash(
 password
 ,%0A%09%09%09%09%09e
@@ -1000,15 +1000,15 @@
 word
+)
 ,%0A%09%09
-%09%09%09
+  
 emai
@@ -1020,28 +1020,39 @@
 ail%0A%09%09%7D)
-.save().exec
+;%0A%0A    return user.save
 ();%0A%09%7D);
@@ -1109,23 +1109,16 @@
 t.find()
-.exec()
 ;%0A%7D%0A%0Aexp
@@ -1496,23 +1496,16 @@
 t.save()
-.exec()
 ;%0A%7D%0A%0A//i
@@ -1620,23 +1620,16 @@
 nd(%7Bid%7D)
-.exec()
 %0A  .then
@@ -1706,15 +1706,8 @@
 ve()
-.exec()
 ;%0A  
@@ -2750,16 +2750,113 @@
 es%5B0%5D);%0A  %7D);%0A%7D%0A
+%0A%0A//Util%0Avar hash = function(pwd)%7B%0A  crypto.createHash('sha256').update(pwd).digest('base64');%0A%7D%0A

Fix bugs in databas.ejs