define([
		'lodash/lodash'
	],
	function() {
		var dataResource = function($q, $http, config) {
			var self = this;
			this.__parameter = {};

			var createURL = function(endpoint, parameters) {
				var params = _.chain(parameters)
					.map(function(value, key) {
						return ([
							key,
							'=',
							encodeURIComponent(value)
						]).join('');
					})
					.value()
					.join('&')

				if(params.length) {
					return ([
						endpoint,
						'?',
						params
					]).join('');
				} else {
					return endpoint
				}
			}

			_.each([
				'endpoint',
				'parameter',
			], function(key) {
				if (!_.isUndefined(config[key])) {
					self['__' + key] = config[key];
				}
			});

			if (!_.isUndefined(config.init)) {
				this.__data = $q.when(config.init);
			} else {
				this.__data = undefined;
			}

			return {
				setEndpoint: function(endpoint) {
					self.__endpoint = endpoint;

					return this;
				},
				setParameters: function(parameters) {
					self.__parameter = parameters;

					return this;
				},
				setParameter: function(name, value) {
					self.__parameter[name] = value;

					return this;
				},
				setHeaders: function(headers) {
					self.__headers = headers;

					return this;
				},
				setRequestTimeout: function(timeout) {
					self.__timeout = timeout;

					return this;
				},


				set: function(promise) {
					self.__data = $q.when(promise);

					return self.__data;
				},
				current: function() {
					return self.__data;
				},
				get: function() {
					self.__data = $http({
						method: 'GET',
						url: createURL(self.__endpoint, self.__parameter),
						cache: false,
						timeout: _.isUndefined(self.__timeout) ? 60000 : self.__timeout,
						headers: _.isUndefined(self.__headers) ? {} : self.__headers,
					})

					return self.__data;
				},
				post: function(payload) {
					self.__data = $http({
						method: 'POST',
						url: createURL(self.__endpoint, self.__parameter),
						cache: false,
						timeout: _.isUndefined(self.__timeout) ? 60000 : self.__timeout,
						headers: _.isUndefined(self.__headers) ? {} : self.__headers,
						data: payload,
					})

					return self.__data;
				},
				put: function(payload) {
					self.__data = $http({
						method: 'PUT',
						url: createURL(self.__endpoint, self.__parameter),
						cache: false,
						timeout: _.isUndefined(self.__timeout) ? 60000 : self.__timeout,
						headers: _.isUndefined(self.__headers) ? {} : self.__headers,
						data: payload,
					})

					return self.__data;
				},
				delete: function(payload) {
					self.__data = $http({
						method: 'DELETE',
						url: createURL(self.__endpoint, self.__parameter),
						cache: false,
						timeout: _.isUndefined(self.__timeout) ? 60000 : self.__timeout,
						headers: _.isUndefined(self.__headers) ? {} : self.__headers,
					})

					return self.__data;
				}
			}
		}

		return dataResource;
	}
)