/**
 * Ldap Search Tool
 */
(function () {
	'use strict';

	angular.module('cla.ldap.connections')
		.directive('searchTool', searchTool);

	searchTool.$inject = ['searchService'];

	/**
	 * @param searchService service
	 */
	function searchTool (service) {
		return {
			controller: controller,
			controllerAs: 'search',
			restrict: 'E',
			scope: { },
			templateUrl: '/interface_default/admin/system/templates/search.directive.html'
		};

		function controller () {
			var search = this;
			this.properties = service.properties;

			this.run = run;
			this.isConnected = isConnected;
			this.newWindow = newWindow;

			/**
			 * run search query
			 */
			function run() {
				if (!search.isConnected()) {
					console.warn('not connected');
					return;
				}

				service.search().then(function (response) {
					search.properties.results = response.result;
				});
			}

			/**
			 * is an ldap connection present
			 * @returns {boolean}
			 */
			function isConnected() {
				return service.isConnected();
			}

			/**
			 * opens a new window and injects search results content in to it.
			 */
			function newWindow() {
				var win = window.open('/admin/system/ldap-search-results', 'newwindow' ,'width=800,height=600');
				win.document.write('<pre>'+ search.properties.results +'</pre>');
			}
		}
	}
}());