'use strict';

app.directive('searchModels', function ($modal, toastr, Database) {
	return {
		restrict: 'A',
		scope: {
			dbType: '=',
			brand: '=',
			query: '=',
			result: '=',
			event: '@' //takes a string for event type, click or keypress (mapped to enter key)
		},
		link: function(scope, element, attrs, ctrl) {
			function updateModel() {
				Database.searchModels(scope.dbType, scope.brand, scope.query)
				.then(function(devices) {
					console.log(devices);
					//scope.device.targetType = null;
					//scope.device.model = null;

					scope.result = devices;

					devices.irSearchResult = false;
					devices.ipSearchResult = false;

					if (!devices.ir.length && !devices.ip.length) {
						$modal({
							title: 'No Models Found',
							content: 'The model you searched for was not found. You may try searching again or choose from the list of popular models.',
							show: true
						});
					}

					if (!devices.ir.length) {
						_.forEach(devices.p_ir, function(device, i) {
							device.index = i;
							scope.result.ir.push(device);  
						});
					} else {
						devices.irSearchResult = true;
					}

					if (!devices.ip.length) {
						_.forEach(devices.p_ip, function(device, i) {
							device.index = i;
							scope.result.ip.push(device);  
						});
					} else {
						devices.ipSearchResult = true;
					}
				})
				.catch(function(error) {
					toastr.error(error, 'Error');
				});     
			}

			if (scope.event === 'click') {    
				element.on('click', function(event) {
					console.log('element clicked');
					scope.$apply(updateModel);
				});
			} else {
				element.bind("keypress", function (event) {
					var key = event.keyCode || event.which;
					if(key === 13) {
						scope.$apply(updateModel);       
					}
				});
			}
			
		}
	};
});