(function () {
	'use strict';

    var ng_module_name = 'pageurl_list';

	angular.module(ng_module_name)
		.directive('pageurlListLoader', pageurlListLoader);

	pageurlListLoader.$inject = ['pageurlListService', '$localStorage'];
	function pageurlListLoader(service, $localStorage)
	{
		var controller = function ($scope, $timeout)
		{
			var ctrl = this;
			ctrl.init = function(site_data, site_perms)
			{
				ctrl.$storage = $localStorage;
				if (ctrl.$storage.hash === undefined || ctrl.$storage.hash === 0 || typeof ctrl.$storage.hash === 'string'){
					ctrl.$storage.hash = [];
				}

				var is_cached = false;
				var hash_length = ctrl.$storage.hash.length;
				for(var i = 0; i < hash_length; i++){
					var name = ctrl.$storage.hash[i];
					if(name === site_data.hash){
						is_cached = true;
						break;
					}
				}
				if (is_cached)
				{
					service.GetData(site_data.urls[0].site_id, function () {
						SetHash(site_data, ctrl.$storage);
						$timeout(function () {
							$scope.$digest();
						}, 0);
					});
				}else {
					service.setUrls(site_data.urls);
					service.setPerms(site_perms);
				}
				SetHash(site_data, ctrl.$storage);

			};
		};
		controller.$inject = ['$scope', '$timeout'];

		function SetHash(site_data, $storage) {
			if ($storage.hash.length >= 20)
			{
				$storage.hash.unshift(site_data.hash);
				$storage.hash.pop();
			}else{
				$storage.hash.push(site_data.hash);
			}
		}

		return {
			replace: false,
			restrict: 'E',
			controller: controller,
			controllerAs: 'loader',
			bindToController: true

		};
	}

}());
