'use strict';

/* globals angular */

/**
 * @ngdoc service
 * @name brandDashboardApp.user
 * @description
 * # user
 * Service in the brandDashboardApp.
 */
angular.module('EnterpriseDashboardApp.UserResource', [])
	.service('User', function user($window, $q, $http, $log, $rootScope, HostFactory) {


		var Service;

		var SCHEME, DATABASE_NAME, COLLECTION_NAME, HOST, URL_PATH;

		DATABASE_NAME = HostFactory.getDbUrlComponent();
		COLLECTION_NAME = 'users';

		SCHEME = HostFactory.getScheme();
		HOST = HostFactory.getHost();

		URL_PATH = SCHEME + '://' + HOST + '/api/' + DATABASE_NAME + '/' + COLLECTION_NAME;


		Service = {
			get: function() {
				if (!$window.sessionStorage.user) {
					return null;
				}
				return JSON.parse($window.sessionStorage.user);
			},
			set: function(user) {
				$log.info(JSON.stringify($window.sessionStorage.user));
				if ($window.sessionStorage.user) {
					$window.sessionStorage.user = null;
				}
				$window.sessionStorage.user = JSON.stringify(user);
				$rootScope.$emit('changeUser');
				$log.info(JSON.stringify($window.sessionStorage.user));
			},
			remove: function() {
				$log.info('Removing user from session');
				delete $window.sessionStorage.user;
				delete $window.sessionStorage.token;
				delete $window.sessionStorage.username;
			},
			login: function(opts) {
				var url;

				url = HostFactory.getScheme() + '://' + HOST + '/login';

				return $http.post(url, opts);
			},
			changePassword: function(password, newPassword) {
				var user, def;

				def = $q.defer();
				user = Service.get();

				$http.put(SCHEME + '://' + HOST + '/user/' + user._id, {
					password: password,
					newPassword: newPassword
				}).success(function(data) {
					$log.info('User updated...');
					def.resolve(data);
				}).error(function(err) {
					$log.info('Error updating user', err);
					def.reject(err);
				});

				return def.promise;
			},
			update: function(user) {
				var def;

				def = $q.defer();

				$http.put(URL_PATH + '/' + user._id, {
					update: user
				}).success(function(data) {
					$log.info('User updated');
					def.resolve(data);
				}).error(function(err) {
					$log.info('Error updating user', err);
					def.reject(err);
				});

				return def.promise;
			}
		};

		return Service;

	});
