/* globals angular */
'use strict';


angular.module('EnterpriseDashboardApp.Encoder', [])
	.service('Encoder', function ProductResource($q, $rootScope, $log) {


		var Encoder = {
			_getLocation: function(href) {
				var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)(\/[^?#]*)(\?[^#]*|)(#.*|)$/);
				return match && {
					protocol: match[1],
					host: match[2],
					hostname: match[3],
					port: match[4],
					pathname: match[5],
					search: match[6],
					hash: match[7]
				};
			},
			_extractRelevantPathByUrl: function(path) {
				var tmp;

				if (path.indexOf('http') === 0) {
					tmp = this._getLocation(path);
					path = tmp.pathname;
				}
				tmp = /^(\/([^\/]+)){3}/gi.exec(path);

				if (!tmp || !tmp.length) {
					tmp = /^(\/([^\/]+)){2}/gi.exec(path);
					if (!tmp || !tmp.length) {
						return null;
					}
				}

				return tmp[0];
			},
			getEventNameByRequest: function(request) {
				var method, tmp;

				method = request.method;
				tmp = this._extractRelevantPathByUrl(request.url);
				if (!tmp) {
					return $log.error('Problem in getting event name by request');
				}
				return method + ' ' + tmp;
			},
			getRestEventNamesByModelUrl: function(modelUrl) {
				var url;

				url = this._extractRelevantPathByUrl(modelUrl);

				return {
					POST: 'POST ' + url,
					GET: 'GET ' + url,
					PUT: 'PUT ' + url,
					DELETE: 'DELETE ' + url
				};
			}
		};

		return Encoder;



	});