<repo_name>edwincarlson/RoundCaddy<file_sep>/public/js/services/SessionService.js
angular.module('SessionService', []).factory('Session', function($rootScope, $location, $cookieStore, socket) {

    var login = function(user){
        var currentUser = $cookieStore.get('user');
        if (currentUser != undefined){
            $cookieStore.remove('user');
            $cookieStore.put("user", user);
            console.log(user);
            $rootScope.username = user.username;
            if(user.role === "owner"){
                $rootScope.noSession = false;
                $rootScope.studentSession = false;
                $rootScope.adminSession = true;
            }
            else if(user.role === "student"){
                $rootScope.noSession = false;
                $rootScope.studentSession = true;
                $rootScope.adminSession = false;
            }
        }
        else{
            $cookieStore.put("user", user);
        }
    }

    // creates new session - user session, admin session
	var createSession = function(course){
        
		if(course.owner === true){
            currentUser= $cookieStore.get('user');
            $cookieStore.remove('user');
            currentUser.currentCourse = {
                _id: course.OrganizationID,
                name: course.Name
            };
            currentUser.session = 'Professor';
            $cookieStore.put('user', currentUser);
            $rootScope.noSession = false;
			$rootScope.studentSession = false;
			$rootScope.adminSession = true;
            $rootScope.username = currentUser.username;
        }
        else if(course.owner === false){
            currentUser= $cookieStore.get('user');
            $cookieStore.remove('user');
            currentUser.currentCourse = {
                _id: course.OrganizationID,
                name: course.Name
            };
            currentUser.session = 'Student';
            $cookieStore.put('user', currentUser);
        	$rootScope.noSession = false;
        	$rootScope.studentSession = true;
        	$rootScope.adminSession = false;
            $rootScope.username = currentUser.username;
        }
        
    }

    // creates new session - no session, user session, admin session
    var checkSession = function(user){   
        if(user === undefined){
            $rootScope.studentSession = false;
            $rootScope.adminSession = false;
            $rootScope.noSession = true;
            //window.location.replace("https://learn.aero.und.edu/index.asp");
            window.close();
        }
        else if(user.role === "owner"){
            $rootScope.noSession = false;
            $rootScope.studentSession = false;
            $rootScope.adminSession = true;
            $rootScope.username = user.username;
            socketUser = {
                        username : user.username,
                        _id      : user._id
                    }
            socket.emit("adduser", socketUser);
        }
        else if(user.role === "student"){
            $rootScope.noSession = false;
            $rootScope.adminSession = false;
            $rootScope.studentSession = true;
            $rootScope.username = user.username;
            socketUser = {
                        username : user.username,
                        _id      : user._id
                    }
            socket.emit("adduser", socketUser);
        }
        
    }

    // terminate current session
    var endSession = function(){
        //delete cookie we created at login
        //$cookieStore.remove('user');
    	$rootScope.username = '';
    	$rootScope.studentSession = false;
		$rootScope.adminSession = false;
        $rootScope.noSession = true;
        //$location.path('/login');
    }
	
	return {
        login         : login,
		createSession : createSession,
        checkSession  : checkSession,
		endSession	  : endSession
  	};
});<file_sep>/public/js/services/CourseService.js
angular.module('CourseService', []).factory('Course', ['$http', function($http) {


	return {
		// call to get all rooms
		getCourses : function(userID) {
			return $http.get('/api/user/courses/' + userID);
		}
	}		

}]);<file_sep>/public/js/services/UserService.js
angular.module('UserService', []).factory('UserService', ['$http', function($http) {

    //user login
    var authenticate = function() {
        return $http.post('/api/authenticate');
    }
    //user logout
    var logout = function(userData) {
        return $http.post('/api/logout', userData);
    } 	

    return {
        authenticate   : authenticate,
        logout   : logout
  	};	
}]);<file_sep>/public/js/controllers/HistoryCtrl.js
angular.module('HistoryCtrl', []).controller('HistoryController', function($scope, $state, $cookieStore, $filter, Room, ngTableParams, $stateParams, Chat, Session) {

	//getting currentuser for session validation
	var currentUser = $cookieStore.get('user');
    if (currentUser != undefined){
        Session.checkSession(currentUser);
    }
    else{
        Session.endSession();
        $state.go('login');
    }

    $scope.currentSession = "All";

    $scope.sessionSelect = function(session){
    	var data = [];
    	$scope.currentSession = session;
    }

    $scope.allMsgs = [];
    $scope.currentSession = null;

    var getData = function(){
    	var sessionMsgs = [];
    	var data = [];
    	if($scope.currentSession === null){
    		return data;
    	}
    	else if($scope.currentSession === "All Days"){
    		$scope.msgs = $scope.allMsgs;
    		data = $scope.allMsgs;
    		return data;
    	}
    	else{
    		for(var i=0; i<$scope.allMsgs.length; i++){
	    		if($scope.currentSession === moment(new Date($scope.allMsgs[i].posted)).format("dddd, MMMM Do YYYY")){
	    			sessionMsgs.push($scope.allMsgs[i]);
	    		}
	    	}
	    	$scope.msgs = sessionMsgs;
	    	data = sessionMsgs
	    	return data;
    	}
    }

	Room.getRoom($stateParams.room)
		.success(function(data, status, headers, config) {	
			$scope.currentRoom = data;
	    });

	Chat.get($stateParams.room)
		//we comminucated with the server
		.success(function(data, status, headers, config) {
			$scope.msgs = [];
			$scope.sessions = [];
			var newSession = null;
	        //received past messages for this room
	        for(var i=0; i<data.length; i++){
	        	var date = data[i].posted;
	        	data[i].posted = moment(date).format('MM/D/YYYY h:mm a');
	        	newSession = moment(new Date(data[i].posted)).format("dddd, MMMM Do YYYY");
	  
        		var count = 0;
        		for(var x=0; x<$scope.sessions.length; x++){
        			if(newSession === $scope.sessions[x]){
        				count++;
        			}
        		}
	        	if(count===0){
	        		$scope.sessions.push(newSession);
	        	}

	        	$scope.allMsgs = data;
	        	$scope.msgs = data;

	        	$scope.currentSession = "All Days";

	        }
	    });

		$scope.$watch("currentSession", function () {
        	$scope.tableParams.reload();
    	});         

		$scope.tableParams = new ngTableParams({
	        page: 1,            // show first page
	        count: 10           // count per page
	    }, {
	        total: function () { return getData().length; }, // length of data
	        getData: function($defer, params) {
	        	// use build-in angular filter
	        	var filteredData = params.filter() ? $filter('filter')(getData(), params.filter()) : getData();
       			var orderedData = params.sorting() ? $filter('orderBy')(filteredData, params.orderBy()) : getData();
       			params.total(orderedData.length); // set total for recalc pagination
	            $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
	        },
	        $scope: { $data: {} }
	    });
});<file_sep>/public/js/controllers/CreateRoomCtrl.js
angular.module('CreateRoomCtrl', []).controller('CreateRoomController', function($scope, $state, $cookieStore, Room, UserService, Session, socket) {

    //initializing user service
    var User = UserService;

    //checking for valid session
    var currentUser = $cookieStore.get('user');
    Session.checkSession(currentUser);

	//date selectors for room creation
	jQuery('#roomStart').datetimepicker();
	jQuery('#roomEnd').datetimepicker();

    //setting course name from current course 
    $scope.course = currentUser.course;

    //reset successMessage
    $scope.successMessage = false;

    $scope.status = "Closed";
    $scope.open = false;

    $scope.openRoom = function(){
        $scope.status = "Open";
        $scope.open = true;
    }

    $scope.closeRoom = function(){
        $scope.status = "Closed";
        $scope.open = false;
    }

    //submit create room form for validation
    $scope.submitCreateRoom = function(isValid){
        var minLength = 0;

        //input fields valid
        $scope.titleValid = false;
        $scope.descriptionValid = false;
        $scope.startValid = false;
        $scope.endValid = false;

        // input fields invalid
        $scope.titleInvalid = false;
        $scope.selectInvalid = false;
        $scope.startInvalid = false;
        $scope.endInvalid = false;

        //form is not valid
        if(isValid === false){
            //title validation
            if($scope.roomCreateForm.title.$valid && $scope.roomCreateForm.title.$pristine === false){
                    $scope.titleValid = true;
            }
            else{
                $scope.titleInvalid = true;
            }

            //description validation if one is supplied
            if($scope.description === ''){
                $scope.descriptionValid = false;
            }
            else if($scope.description === undefined){
                $scope.descriptionValid = false;
            }
            else{
                $scope.descriptionValid = true;
            }

            //start date validation if one is supplied
            if($('#roomStart').val() === ''){
                $scope.startValid = false;
            }
            else if($('#roomStart').val() === undefined){
                $scope.startValid = false;
            }
            else{
                if(moment().isAfter(new Date($('#roomStart').val()))){
                    $scope.startInvalid = true;
                    $scope.startMessage = "Start Date must be after the current date and time."
                }
                else{
                    $scope.startValid = true;
                } 
            }

            //end date validation if one is supplied
            if($('#roomEnd').val() === ''){
                $scope.endValid = false;
            }
            else if($('#roomEnd').val() === undefined){
                $scope.endValid = false;
            }
            else{
                if(moment(new Date($('#roomStart').val())).isAfter(new Date($('#roomEnd').val()))){
                    console.log("here")
                    $scope.endInvalid = true;
                    $scope.endMessage = "End Date must be after the Start date and time.";
                }
                else if(moment().isAfter(new Date($('#roomEnd').val()))){
                    $scope.endInvalid = true;
                    $scope.endMessage = "End Date must be after the current date and time.";
                }
                else{
                    $scope.endValid = true;
                }
            }
        }

        //form is valid
        if(isValid){
            $scope.titleValid = true;
            $scope.submitStart = true;
            $scope.submitEnd = true;

            //description validation if one is supplied
            if($scope.description === ''){
                $scope.descriptionValid = false;
            }
            else if($scope.description === undefined){
                $scope.descriptionValid = false;
            }
            else{
                $scope.descriptionValid = true;
            }

            //start date validation if one is supplied
            if($('#roomStart').val() === ''){
                $scope.startValid = false;
            }
            else if($('#roomStart').val() === undefined){
                $scope.startValid = false;
            }
            else{
                if(moment().isAfter(new Date($('#roomStart').val()))){
                    $scope.startInvalid = true;
                    $scope.startMessage = "Start Date must be after the current date and time."
                    $scope.submitStart = false;
                }
                else{
                    $scope.startValid = true;
                } 
            }

            //end date validation if one is supplied
            if($('#roomEnd').val() === ''){
                $scope.endValid = false;
            }
            else if($('#roomEnd').val() === undefined){
                $scope.endValid = false;
            }
            else{
                if(moment(new Date($('#roomStart').val())).isAfter(new Date($('#roomEnd').val()))){
                    $scope.endInvalid = true;
                    $scope.endMessage = "End Date must be after the Start date and time.";
                    $scope.submitEnd = false;
                }
                else if(moment().isAfter(new Date($('#roomEnd').val()))){
                    $scope.endInvalid = true;
                    $scope.endMessage = "End Date must be after the current date and time.";
                    $scope.submitEnd = false;
                }
                else{
                    $scope.endValid = true;
                }
            }

            if($scope.submitStart === true && $scope.submitEnd === true){
                createRoom();
            }
            
        }
    };

	//function for create room form
	var createRoom = function(){
		//create JSON data of room
        console.log($scope.description);
        if($scope.description === '' || $scope.description === undefined){
            $scope.description = "No Schedule";
        }

		var room = {
			title       : $scope.roomTitle,
			description : $scope.description,
            courseID    : currentUser.courseID,
			start       : $('#roomStart').val(),
			end         : $('#roomEnd').val(),
            open        : $scope.open
		}

		//Call Room Service create which posts to db
		Room.create(room)
            //we comminucated with the server
            .success(function(data, status, headers, config) {
                //room was created
                if(room.start === ''){
                    room.start = null;
                }
                if(room.end === ''){
                    room.end = null;
                }
                room._id = data.id;
                socket.emit('createRoomReq', room);
                $scope.successMessage = true;
                $scope.alertMessage = "Room successfully created!"

                //Reseting values after creating room
                $scope.roomTitle = "";
                $scope.description = "";
                $('#roomStart').val("");
                $('#roomEnd').val("");
                $scope.status = "Closed";
                $scope.open = false;
            })
            .error(function(data, status, headers, config) {
                //not good
                console.log(data);
                console.log(status);
                console.log(headers);
                console.log(config);
            });
	};

});<file_sep>/public/js/app.js
var app = angular.module('golfApp', [
	'ngCookies',
	'ui.router',
	'appRoutes',
	'ui.bootstrap',
	// 'RoomsCtrl', 
	// 'ChatCtrl', 
	// 'ChatService', 
	// 'CreateRoomCtrl', 
	// 'RoomService',
	// 'EditRoomCtrl',
	'LoginCtrl',
	// 'UserService',
	// 'TokenInterceptorService',
	// 'SessionService',
	 'ProfileCtrl',
	// 'SocketService',
	// 'HistoryCtrl',
	// 'CourseService',
	// 'CoursesCtrl'

]);

// app.factory("socket", function(){
//  	var socket = io.connect('http://localhost:3000');
//  	return socket;
// });

// app.config(function($httpProvider){
// 	$httpProvider.interceptors.push('TokenInterceptor');
// });

// app.run(function($rootScope, $state, $cookieStore, Session) {
//     $rootScope.$on("$stateChangeStart", function(event, next) {
//         if (next.access.requiredLogin && $cookieStore.get('user') === undefined) {
//         	Session.endSession();
//         	$rootScope.accessMessage = "Must be logged in to access that feature.";
//         	$rootScope.accessError   = true;
//         }

//     });

// });