<repo_name>moak/dumbo<file_sep>/app/www/js/services/tournamentQueue.js
angular.module('starter')

.factory('TournamentQueue', function($http, $q, $log) {

		var httpOptions = function () {
				return {headers: {'Content-Type': 'application/json'}};
		};

		var TournamentQueue = function() {
		};

		TournamentQueue.prototype.fetch = function() {
				var deferred = $q.defer();

				$http.get('http://localhost:8080/api/tournaments/fetch')
						.success(function(data) {
							console.log(data);
								deferred.resolve(data);
						})
						.error(function(err, code) {
								deferred.reject(err);
						$log.error(err, code);
				});
				return deferred.promise;
		};

		return TournamentQueue;
});
<file_sep>/app/www/js/controllers/profileCtrl.js
angular.module('starter.profileCtrl', [])

.controller('ProfileCtrl', function($scope, $ionicModal, $timeout, ngFB  ) {

  ngFB.api({
       path: '/me',
       params: {fields: 'id,name'}
   }).then(
       function (user) {
           $scope.user = user;
       },
       function (error) {
           alert('Facebook error: ' + error.error_description);
       });
});
<file_sep>/app/www/js/services/Auth.js
angular.module('starter')

.factory('Auth', function($http, $q, $log, $window) {

		return {
			isAuth : function() {
			 	return $window.localStorage['token'] !== undefined;
			},
			getToken : function() {
					return $window.localStorage['token'];
			},
			logout : function() {
			 	return $window.localStorage['token'] = undefined;
			},
			getUser : function() {
					var user = {
						id : $window.localStorage['id'],
						token : $window.localStorage['token'],
						name : $window.localStorage['name']
					};

					return user;
			}
		};

});
<file_sep>/app/www/js/controllers/loginFBCtrl.js
angular.module('starter.loginFBCtrl', [])

.controller('LoginFBCtrl', function($scope, $ionicModal, $timeout, ngFB, $window , $location,  $state, $ionicHistory, ngFB, Player ) {

  $ionicHistory.nextViewOptions({
   disableBack: true
 });

    $scope.fbLogin =  function(){
        ngFB.login({scope: 'email,publish_actions'}).then(
        function (response) {
            if (response.status === 'connected') {
                ngFB.api({
                     path: '/me',
                     params: {fields: 'id,name'}
                 }).then(function (user) {
                     var player = new Player(user.id, response.authResponse.accessToken, user.name );
                     player.save();
                     $state.go('app.tournaments')
                 },
                 function (error) {
                     alert('Facebook error: ' + error.error_description);
                 });
            } else {
                alert('Facebook login failed');
            }
        });
    };

});
<file_sep>/app/www/js/services/tournament.js
angular.module('starter')

.factory('Tournament', function($http, $q, $log) {

		var Tournament = function(name) {
				this.name = name;
		};

		var httpOptions = function () {
	      return {headers: {'Content-Type': 'application/json'}};
	  };

		Tournament.prototype.create = function(name) {
				var deferred = $q.defer();
				var body = {
						name : this.name
				};
				$http.post('http://localhost:8080/api/tournament/create', body, httpOptions())
						.success(function(data) {
								deferred.resolve(data);
						})
						.error(function(err, code) {
								deferred.reject(err);
						$log.error(err, code);
				});
				return deferred.promise;
		};

		Tournament.prototype.fetch = function(id) {
				var deferred = $q.defer();
				var url = 'http://localhost:8080/api/tournaments/' + id + '/fetch';

				$http.get(url)
						.success(function(data) {
								deferred.resolve(data);
						})
						.error(function(err, code) {
								deferred.reject(err);
						$log.error(err, code);
				});
				return deferred.promise;
		};

		return Tournament;
});
<file_sep>/app/www/js/services/player.js
angular.module('starter')

.factory('Player', function($http, $q, $log, $window) {

		var Player = function(id,token,name) {
				this.id = id;
				this.token = token;
				this.name = name;
		};

		var httpOptions = function () {
	      return {headers: {'Content-Type': 'application/json'}};
	  };
		Player.prototype.save = function() {
				$window.localStorage['id'] = this.id;
				$window.localStorage['token'] = this.token;
				$window.localStorage['name'] = this.name;
		};

		Player.prototype.getPlayer = function() {
				return new Player(this.id, this.token, this.name);
		};

		Player.prototype.register = function(idTournament) {
			console.log(this);
				var deferred = $q.defer();
				var body = {
						name : this.name,
						token : this.token,
						id : this.id
				};

				console.log(body);

				$http.post('http://localhost:8080/api/tournaments/'  + idTournament +  '/register', body, httpOptions())
						.success(function(data) {
								deferred.resolve(data);
						})
						.error(function(err, code) {
								console.log(err);
								deferred.reject(err);
						$log.error(err, code);
				});
				return deferred.promise;
		};

		return Player;
});
<file_sep>/app/www/js/controllers/createCtrl.js
angular.module('starter.createCtrl', [])

.controller('CreateCtrl', function($state , $scope, $ionicModal, $timeout, Tournament, $ionicHistory) {

    $ionicHistory.nextViewOptions({
     disableBack: true
   });

    $scope.create = function(name) {
        var t = new Tournament(name);
        t.create(name).then(function(res){
              $state.go('app.tournaments');
        });
    };

});
<file_sep>/app/www/js/controllers/tournamentCtrl.js
angular.module('starter.tournamentCtrl', [])

.controller('TournamentCtrl', function($scope, $ionicModal, $timeout, Tournament, Player, $stateParams, Auth  ) {

  var  t = new Tournament();

  t.fetch($stateParams.id).then(function(result){
      console.log(result);
      $scope.tournament = result;
  });

  $scope.register = function() {
    var player = Auth.getUser();

      var p  = new Player(player.id, player.token, player.name);

      p.register($stateParams.id).then(function(res){
          console.log(res);
      });
  };

});
<file_sep>/api/server.js

var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

var mongoose = require('mongoose');


var Tournament = require("./models/tournament");

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());


app.all('*', function(req, res, next) {
       res.header("Access-Control-Allow-Origin", "*");
       res.header("Access-Control-Allow-Headers", "X-Requested-With");
       res.header('Access-Control-Allow-Headers', 'Content-Type');
       next();
});


var port = process.env.PORT || 8080;        // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {

    res.json({ message: 'hooray! welcome to our api!' });
});

// create a tournament
router.post('/tournament/create', function(req, res) {

    var name = req.body.name;

    if(!name) {
        return res.status(404).send("Name missing");
    }
    Tournament.count({name : name}, function (err, count){
        if( count > 0 ){
            return res.status(404).send("Tournament exsists");
        }
        else {
            var t = new Tournament({name: name});
            t.save(function (err) {
                if (err) {
                  return err;
                }
                else {
                  return res.json(t);
                }
            });
        }
    });
});


router.post('/tournaments/:id/register', function(req,res){
    var _id = mongoose.Types.ObjectId.fromString(req.params.id);
    var query = {"_id": _id};
    var options = {upsert: true};
    var player = { id : req.body.id, token : req.body.token, name : req.body.name };

    console.log(player);

    Tournament.findOneAndUpdate(req.params.id, {$push: { players: player }}, options, function(err, tournamentsDB) {
        console.log(err);
        console.log(tournamentsDB);
        if (err) {
          console.log('got an error');
          return res.status(404).send(err);
        }

        if (!tournamentsDB) {
            return res.status(404).send("Tournament doest not exsist");
        }
        else {
            return res.json(tournamentsDB);
        }
    });
});


router.get('/tournaments/:id/fetch', function(req,res){
    var _id = mongoose.Types.ObjectId.fromString(req.params.id);

    Tournament.findById(_id, function(err,tournamentsDB) {
      if (!tournamentsDB)
          return res.status(404).send("Tournament doest not exsist");
      else {
          return res.json(tournamentsDB);
      }
    });
});


router.get('/tournaments/fetch', function(req,res){

    Tournament.find({}, function(err,tournamentsDB) {
      if (!tournamentsDB)
          return res.status(404).send("Tournament doest not exsist");
      else {
          return res.json(tournamentsDB);
      }
    });
});


router.get('/tournaments', function(req,res){
    Tournament.find().all(function(tournaments) {

      res.json(tournaments);
    });
});
// more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
<file_sep>/api/models/tournament.js
var mongoose = require("mongoose");

//connect to database
var db = mongoose.connect('mongodb://localhost/dumbo');


var playerSchema = new mongoose.Schema({
    name: String,
    date: { type: Date, default: Date.now },
});

//create schema for blog post
var tournamentSchema = new mongoose.Schema({
  name:  String,
  author: String,
  //players: [playerSchema],
  players : [],
  created: { type: Date, default: Date.now }
});

//compile schema to model
module.exports = db.model('tournament', tournamentSchema);
