(function(){

    'use strict';

    angular.module('PortalSearch').controller('searchController', searchController);

    searchController.$inject = ['$rootScope', '$scope', '$timeout', '$window','$location', '$routeParams', '$anchorScroll', '$filter', '$translate', 'stateService'];

	function searchController($rootScope, $scope, $timeout, $window, $location, $routeParams, $anchorScroll, $filter, $translate, stateService){

		var translateFilter = $filter('translate');

		var context = this;

		this.allField = null;
		this.exactField = null;
		this.noneField = null;
		this.localeFilter = null;
		this.topQueries = null;

		this.getSearch = function () {
			var context = this;
			var lang = $translate.use();
			$window.location.href = "/wps/portal/Home/search/#/searchResults?q=" + context.query;
		};
			
		this.getTopQueries = function () {
			var context = this;
			var lang = $translate.use();

			var defaultRowCount = parseInt(translateFilter('defaultRowCount'));
			
			var options = {
				"isCustomSearch": false,
				"searchLocale": lang,
				"query": null,
				"usePagingParam": true,
				"searchType": "topQueries",
				"rowsNumber": defaultRowCount,
				"startRowNumber": 0,
				"findAllWordsQuery": null,
				"exactMatchQuery": null,
				"excludeWordsQuery": null,
				"fromDateFilter": null,
				"toDateFilter": null,
				"contentFormatFilter": null,
				"localeFilter": null,
				"relatedEntityFilter": null,
				"lifeEventFilter": null,
				"sourceFilter": null,
				"categoryFilter": null,
				"sectorFilter": null,
				"isAllDatesFacetQuery": null,
				"isPastMonthFacetQuery": null,
				"isPastYearFacetQuery": null,
				"fromDateFacetQuery": null,
				"toDateFacetQuery": null,
				"isSortByPublishDate": false
			};
			stateService.getSearch(options).then(
				function(response){
				  context.handleTopQueries(response.data);
				},
				function(error){
				  console.log(error);
			});
		};
			
		this.handleTopQueries = function (topQueriesArray){
			var context = this;
			context.topQueries = [];
			if(topQueriesArray && topQueriesArray.length > 0){
				//Build an array of the top queries (Add only the queries that have the words between asterisks)
				topQueriesArray.forEach(function(topQuery){
					//if(topQuery.key.indexOf(":") == -1){
						//var queryLabel = topQuery.key.match(/\*\s*([^*]*?)\s*\*/g);
						//var queryLabel = topQuery.key.match(/(\(*([^)]*)\)*)/g);
						var queryLabel = topQuery.key.match(/(\(+([^)]*)\)+)/i);
						if(queryLabel && queryLabel.length > 0){
							if(queryLabel[0].indexOf(":") == -1){
								queryLabel = queryLabel[0].toLowerCase().trim().replace(/\(/g, "").replace(/\)/g, "").replace(" and", "");
								context.topQueries.push({ 'label': queryLabel, 'value': topQuery.key.toLowerCase() });
							}
						}
					//}
				});
				//Remove duplicates
				var dupes = {};
				var uniqueSuggestions = [];
				var lst = context.topQueries;
				$.each(lst, function(i, el) {
					if (!dupes[el.label]) {
						dupes[el.label] = true;
						uniqueSuggestions.push(el);
					}
				});
				context.topQueries = uniqueSuggestions;
				
				if(context.topQueries.length > 6){
					context.topQueries = context.topQueries.slice(0, 6);
				}
			}
		};
			
		this.getResultForQuery = function (query){
			var context = this;
			var lang = $translate.use();

			var defaultRowCount = parseInt(translateFilter('defaultRowCount'));
			if(query != null && query != ""){
				$window.location.href = "/wps/portal/Home/search/#/searchResults?q=" + query;
			}
		};
		
		this.enableSubmit = function () {
			return (this.query != null && this.query != '');
		};

		this.init = function (lang) {
          $anchorScroll();
          var context = this;
          var lang = $translate.use();
		  try{
			lang == "en" ? this.showEnglish = true : this.showEnglish = false;
			context.getTopQueries();
            $("#manageMain").show();
		  } catch (e){
			console.log(e);
		  }
		  this.searchResult = [];
		  this.haveResults = false;
		};
		this.init();
	}
})();
