(function(){

    'use strict';

    //			Service to provide data and temporary storage
    angular.module('PortalSearch').factory('stateService', stateService);

	stateService.$inject = [ '$rootScope', '$http','$translate', '$filter' ];

	function stateService($rootScope, $http, $translate, $filter){

      	var translateFilter = $filter('translate');

      	var searchResults = null;
		var options = null;
        var facets = [];

		return {
			searchResults: searchResults,
			options: options,
			facets: facets,
			getLookups: getLookups,
			getSearch: getSearch,
			addFacets: addFacets,
			getAutocomplete: getAutocomplete,
			removeFacets: removeFacets,
			getFacets: getFacets,
			hasNull: hasNull,
			getMessage: getMessage
		};
		
		function getMessage (messageLabel){
			return translateFilter(messageLabel);
		}

		function getLookups (){
			var context = this;
			var lookupURL = "/MoictLookups/lookups";
			return $http.get(lookupURL);
		}

		function addFacets (newFacets){
		  var context = this;
		  this.facets.push(newFacets);
		  $rootScope.$broadcast("facetsUpdated", { 'facets': this.facets });
		}

		function removeFacets (facet){
		  var context = this;
		  var facetIndex = this.facets.indexOf(facet);
		  if(facetIndex != -1){
			context.facets.splice(facetIndex, 1);
		  }
		  $rootScope.$broadcast("facetsUpdated", { 'facets': this.facets });
		}

		function getFacets (){
		  var context = this;
		  return this.facets;
		}

		function getAutocomplete(suggestTerm){
		  
		  var options = {
			  "isCustomSearch": true,
			  "query": (suggestTerm != null && suggestTerm != '') ? suggestTerm : '',
			  "usePagingParm": true,
			  "searchType": "suggest",
			  "rowsNumber": 10,
			  "startRowNumber": 0,
			  "findAllWordsQuery": null,
			  "exactMatchQuery": null,
			  "excludeWordsQuery": null,
			  "fromDateFilter": null,
			  "toDateFilter": null,
			  "contentFormatFilter": null,
			  "localefilter": null,
			  "relatedEntityFilter": null,
			  "sourcefilter": null,
			  "categoryfilter": null,
			  "isAllDatesFacetQuery": null,
			  "isPastMonthFacetQuery": null,
			  "isPastYearFacetQuery": null,
			  "fromDateFacetQuery": null,
			  "toDateFacetQuery": null
		  }
		  
		  return $http.post('/Search/portal/contents', options);
		}

		function getSearch(options){
			return $http.post('/Search/portal/contents', options);
		};

		function hasNull (target){
			for (var member in target) {
			  if (target[member] != null && target[member] != '')
				  return false;
			}
			return true;
		}
	}
})();
