/* globals $ */

'use strict';

/**
 * @ngdoc directive
 * @name annotationAppApp.directive:productFilterUiComponent
 * @description
 * # productFilterUiComponent
 */
angular.module('app')
	.directive('productFilterUiComponent', function($log, $rootScope, RealtimeProductResource) {
		return {
			template: require('./product-filter-ui-component.html'),
			restrict: 'E',
			link: function postLink(scope, element, attrs) {

				scope.currentProduct = null;
				scope.isOpen = false;
				scope.query = '';
				// scope.products = [{
				// 	productName: 'nome prodotto 1'
				// }, {
				// 	productName: 'nome prodotto 2'
				// }];

				if (!scope.products) {
					scope.products = [];
					scope.products = RealtimeProductResource.queryAll().then(function(products) {
						scope.productsToShow = scope.products = products.sort(function(e1, e2) {
							return (e1.brandName + e1.productName) < (e2.brandName + e2.productName);
						});
					});
				} else {
					scope.productsToShow = scope.products;
				}

				scope.addFilter = function(product) {
					scope.currentProduct = product;
					$log.info(JSON.stringify(product));
					scope.isOpen = false;
					$rootScope.$emit('ProductFilter.filterByProduct', product);
				};
				scope.removeFilter = function() {
					scope.currentProduct = false;
					scope.isOpen = false;
					$rootScope.$emit('ProductFilter.removeCurrentFilter');
				};

				scope.addFocusToInput = function() {
					$('.product-filter-input').focus();
				};

				scope.toggleDropDown = function(isOpen) {
					if (isOpen) {
						scope.addFocusToInput();
					}
				};
				scope.filterProductList = function(ps, query) {
					var result;
					// console.log('----------->', !query || query === '', query)
					if (!query || query === '') {
						return ps;
					}
					result = ps.filter(function(p) {
						// console.log('>>', p.productName.toLowerCase().indexOf(query.toLowerCase()) >= 0, p.productName.toLowerCase().indexOf(query.toLowerCase()), p.productName, query)
						return p.productName.toLowerCase().indexOf(query.toLowerCase()) >= 0;
					});
					return result;
				};
				scope.updateProductList = function(query) {
					var result = scope.filterProductList(scope.products, query);
					scope.productsToShow = result;
				}



			}
		};
	});