define([ 'angular' ], function(angular) {
	'use strict';
	angular.module('common.services', [ ]).factory('SessionService', function() {
		return {
			get : function(key) {
				return sessionStorage.getItem(key);
			},
			set : function(key, val) {
				return sessionStorage.setItem(key, val);
			},
			unset : function(key) {
				return sessionStorage.removeItem(key);
			}
		};
	}).factory('AuthenticationService', function($http, SessionService, SerializerUtil) {
		var cacheSession = function() {
			SessionService.set('authenticated', true);
		};
		var uncacheSession = function() {
			SessionService.unset('authenticated');
		};
		var getRootPath = function() {
			var fullPath = window.document.location.href;
			var path = window.document.location.pathname;
			var pos = fullPath.indexOf(path);
			return fullPath.substring(0, pos) + path.substring(0, path.substr(1).indexOf('/') + 1);
		};
		var rootPath = getRootPath();
		return {
			login : function(user) {
				var payload = SerializerUtil.param(user);
				var config = {
					headers : {
						'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
					}
				};
				var login = $http.post(rootPath + "/j_spring_security_check", payload, config);
				login.success(cacheSession);
				return login;
			},
			logout : function() {
				var logout = $http.get(rootPath + "/j_spring_security_logout");
				logout.success(uncacheSession);
				return logout;
			},
			isAuthed : function() {
				return SessionService.get('authenticated');
			},
			getAuthentication : function() {
				var request = $http.get(rootPath + '/authentication');
				request.success(function(data){
					if(data)
						cacheSession();
					else
						uncacheSession();
				});
				request.error(uncacheSession);
				return request;
			}
		};
	}).factory('SerializerUtil', function() {
		return {
			/**
			 * @description 将元素值转换为序列化的字符串表示
			 */
			param : function(obj) {
				var query = '', name, value, fullSubName, subName, subValue, innerObj, i, me = this;
				for (name in obj) {
					value = obj[name];
					if (value instanceof Array) {
						for (i = 0; i < value.length; ++i) {
							subValue = value[i];
							fullSubName = name + '[' + i + ']';
							innerObj = {};
							innerObj[fullSubName] = subValue;
							query += me.param(innerObj) + '&';
						}
					} else if (value instanceof Object) {
						for (subName in value) {
							subValue = value[subName];
							fullSubName = name + '[' + subName + ']';
							innerObj = {};
							innerObj[fullSubName] = subValue;
							query += me.param(innerObj) + '&';
						}
					} else if (value !== undefined && value !== null)
						query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
				}
				return query.length ? query.substr(0, query.length - 1) : query;
			}
		};
	});
});