define(
	['Global', 'Resources'],
	function(Global, resources) {
		var UserSession = Backbone.Model.extend({
			initialize: function(data, config) {
				config = $.extend(config, {});
				this.url = resources.get('public-user-session').get('href');
				this.fetch({
					async: false,
					cache: false
				});
				this.set("sessionTimeoutIn", this.get("clientTimeout") );
				this.set("timeUnits", "minutes" );
				var sessionTimer = _.once(this._sessionTimer);
				if( !/false/.test(config.trackSession) ){
					sessionTimer.call(this);
				}
			},
			isLoggedIn: function() {
				var loggedIn = false;
				var mhpUser = this.get('mhpuser');
				
				if (typeof mhpUser !== 'undefined' && mhpUser) {
					loggedIn = true;
				}

				return loggedIn;
			},
			_sessionTimer: function(){
				var that					= this;
				var minuteAsMilliseconds 	= 60 * 1000;
				var warningThreshold 		= 3 * minuteAsMilliseconds;
				var triggerTimeout			= 0;
				var logoutThreshold			= 0;
				var logoutTimer;

				function checksession(){
					$.ajax({
						url: resources.get('last-accesstime').toJSON().href,
						dataType: 'json',
						global: false,
						success: function(data){
							logoutThreshold = data.timeToExpireInSeconds * 1000;
							var minutes 	= logoutThreshold/1000/60;
							var timeLeft 	= Math.floor(minutes);
							var fix			= (timeLeft <= 0 && logoutThreshold > 0 ) ? 1 : 0;
							timeLeft += fix;
							if(timeLeft < 0){
								timeLeft = 0;
							}
							that.set("sessionTimeoutIn", timeLeft );
							that.set("timeUnits", timeLeft === 1 ? "minute" : "minutes" );
							triggerTimeout = logoutThreshold - warningThreshold;
							if( logoutThreshold <= warningThreshold && logoutThreshold > 0 ){
								Global.getUtilities().eventAggregator.trigger("show:session:warning");
								startCountDown();
							}
							else if( timeLeft <= 0 || logoutThreshold <= 0 ){
								clearTimeout(countdownTimer);
								clearTimeout(logoutTimer);
								Global.getUtilities().eventAggregator.trigger("show:session:expired");
							}
							else{
								sessionTimeout();
							}
						}
					});
				}

				function startCountDown(){
					countdownTimer = setTimeout(function(){
						checksession();
					}, 60000 );
				}

				function sessionTimeout(){
					logoutTimer = setTimeout(function(){
						checksession();
					}, Math.abs(triggerTimeout) );
				}

				checksession();
			}
		});

		UserSession.singleInstance = null;

		UserSession.instance = function () {
			UserSession.singleInstance = UserSession.singleInstance || new UserSession();
			return UserSession.singleInstance;
		};
		
		return UserSession;
	}
);