'use strict';
define(['app'], function(app) {
	app.factory('Auth', ['$http', '$rootScope', '$cookieStore', function($http, $rootScope, $cookieStore){

	    var accessLevels = globals.accessLevels
	        , userRoles = globals.userRoles
	        , RootPath = globals.RootPath
	        , ConsumerKey = globals.ConsumerKey;

	    $rootScope.user = $cookieStore.get('user') || { username: '', role: userRoles.public };
	    //console.log("$rootScope.user: ")
	    //console.log($rootScope.user);
	    //$cookieStore.remove('user');

	    $rootScope.accessLevels = accessLevels;
	    $rootScope.userRoles = userRoles;

	    return {
	        authorize: function(accessLevel, role) {
	            if(role === undefined)
	                role = $rootScope.user.role;
	            return accessLevel & role;
	        },
	        isLoggedIn: function(user) {
	            if(user === undefined) {
	                user = $rootScope.user;
	                //console.log($rootScope.user);
	            }

	            
	            //console.log("-----------------")
	            //console.log("user.role: " + user.role);
	            return user.role === userRoles.user || user.role === userRoles.admin;
	        },
	        register: function(user, success, error) {
	            $http.post('/register', user).success(success).error(error);
	        },
	        login: function(user, success, error) {
	        	//$http.jsonp(globals.RootPath + '/users?callback=JSON_CALLBACK&ConsumerKey=' + globals.ConsumerKey + '&user_email=' + user.username + '&password=' + user.password)
	            //$http({method: 'GET', url: globals.RootPath + '/users?' + '&user_email=' + user.username + '&password=' + user.password, headers: {'ConsumerKey': globals.ConsumerKey}})
	            $http({
	            	method: 'GET', 
	            	//url: RootPath + '/proxy.php?url=users&user_email=' + user.username + '&password=' + user.password,
	            	url: RootPath + '/users?user_email=' + user.username + '&password=' + user.password + '&callback=LOGIN_SUCCESS',
	            	headers: {'ConsumerKey': ConsumerKey}
	        	})
	            .success(function(res, status){
	                //$rootScope.user = user;
	                success(res, status);
	            })
	            .error(function(res, status){
	            	console.log('data: ' + res);
	            	console.log('status: ' + status);

	            	error(res, status);
	            });
	        },
	        logout: function(success, error) {
	            //$http.post('/logout').success(function(){
	                $rootScope.user.username = '';
	                $rootScope.user.role = userRoles.public;
	                $cookieStore.remove('user');
	                success();
	            //}).error(error);
	        },
	        accessLevels: accessLevels,
	        userRoles: userRoles
	    };
	}]);
});