(function () {
	'use strict';
    var ng_module_name = 'tile_settings';

	angular.module(ng_module_name)
		.directive('tileSettings', ['$timeout', settings]);

	function settings($timeout) {
		var directive = {
			controller: controller,
			controllerAs: 'settings',
			replace: false,
			restrict: 'E',
			templateUrl: '/intranet/pages/html/includes/settings_content.html'
		};

		return directive;
		//////////////////

		/** directive controller */
		function controller($scope, $element) {
			var ctrl = this;
			ctrl.width = 'small';
			ctrl.tile = {};

			ctrl.init = function(tile_id)
			{
				ctrl.tile = cla.pages.tileCollection.getTileById(tile_id);
				for (var option in ctrl.tile.options)
				{
					if (ctrl.tile.options.hasOwnProperty(option))
					{
						if (ctrl.tile.options[option].width === 'large')
							ctrl.width = 'large';
						if ((ctrl.tile.options[option].width === 'medium') &&
							(ctrl.width !== 'large'))
						{
							ctrl.width = 'medium';
						}

						if ((ctrl.tile.options[option].input === 'user_picker') ||
							(ctrl.tile.options[option].input === 'group_picker') ||
							(ctrl.tile.options[option].input === 'role_picker') ||
							(ctrl.tile.options[option].input === 'folder_picker') ||
                            (ctrl.tile.options[option].input === 'document_picker') ||
							(ctrl.tile.options[option].input === 'image_picker') ||
							(ctrl.tile.options[option].input === 'html_editor'))
						{
							ctrl.tile.options[option].token = ctrl.tile.options[option].token || {};
						}

						if (ctrl.tile.options[option].input === 'int')
						{
							if (typeof ctrl.tile.options[option].min === 'undefined')
								ctrl.tile.options[option].min = '';
							if (typeof ctrl.tile.options[option].max === 'undefined')
								ctrl.tile.options[option].max = '';
						}

						if (ctrl.tile.options[option].input === 'boolean')
							ctrl.tile.options[option].input = 'bool';

						if (ctrl.tile.options[option].input === 'radio')
							ctrl.tile.options[option].value = '' + ctrl.tile.options[option].value;
					}
				}
			};

			ctrl.onButtonClick = function(option)
			{
				if (option.mutate_on_change)
				{
					option.value = true;
					ctrl.tile.mutateOnChange();
					option.value = false;
				}

				if (option.use_ajax === true)
				{
					var select = angular.element("#" + id);
					var value = select.val();

					ctrl.tile.options[name].value = value;

					$timeout(function() {
						select.find('option').remove();
						select.append($('<option>').attr('value', '' + value).text(value).attr('selected', 'selected'));
					}, 0);
				}

			};

			ctrl.onChange = function(option)
			{
				if (option.mutate_on_change)
					ctrl.tile.mutateOnChange();
			};

			ctrl.onCollapseClick = function(option, $event)
			{
				$event.preventDefault();

				// Clicking the glyphicon tries to close the popover so tell it not to...
				window.cla.pagesEdit.popoverAutoClose = false;

				option.value = !option.value;

				$timeout(function()
				{
					window.cla.pagesEdit.popoverAutoClose = true;
				}, 0);

				if (option.mutate_on_change)
					ctrl.tile.mutateOnChange();
			};

            ctrl.onLabelClick = function(option)
            {
                // Clicking the label tries to close the popover so tell it not to...
                window.cla.pagesEdit.popoverAutoClose = false;

                $timeout(function()
                {
                    window.cla.pagesEdit.popoverAutoClose = true;
                }, 0);

                if (option.mutate_on_change)
                    ctrl.tile.mutateOnChange();
            };

			ctrl.isCustomType = function(option)
			{
				return (typeof option.input_fragment !== 'undefined');
			};

			$scope.select2ify = function()
			{
				var iconPickerTemplate = function(icon)
				{
					if (!icon.id) { return icon.text; }
					return $('<span class="icon-picker-row"><span style="" class="glyphicons glyphicons-' + icon.text + ' icon-picker-row icon-picker-icon"></span> ' + icon.text + '</span>');
				};

				$timeout(function()
				{
					$element.find('.js-options-select, .js-options-multiselect').each(function()
					{
						var name = $(this).prop('name');
						var placeholder = '';

						if (name === '')
							return;

						// Force int value(s) to be a string because Select2 needs it to be one
						if (typeof ctrl.tile.options[name].value === 'number')
							ctrl.tile.options[name].value = '' + ctrl.tile.options[name].value;
						else if ((typeof ctrl.tile.options[name].value === 'object') &&
								 (ctrl.tile.options[name].value !== null))
						{
							for (var i = 0; i < ctrl.tile.options[name].value.length; i++)
							{
								if (typeof ctrl.tile.options[name].value[i] === 'number')
									ctrl.tile.options[name].value[i] = '' + ctrl.tile.options[name].value[i];
							}
						}

						if (typeof ctrl.tile.options[name].placeholder !== 'undefined')
						{
							placeholder = ctrl.tile.options[name].placeholder;
							if (ctrl.tile.options[name].options.length === 0)
								$(this).html('<option></option>');
						}
						var select_options = {placeholder: placeholder};
						if (ctrl.tile.options[name].use_ajax)
						{
							select_options.ajax = {
								url: '/api/pages/components/field_lookup',
								dataType: 'json',
								delay: 250,
								data: function (params) {
									var query = {
										term: params.term,
										page: params.page || 1,
										tile_id: ctrl.tile.id,
										field_name: name
									};
									// Query parameters will be ?search=[term]&page=[page]
									return query;
								},
								processResults: function (data) {
									return {
										results: data.results,
										pagination: {
											more: data.pagination.more
										}
									};
								},
								cache: true
							}

						}


						$(this).select2(select_options);

						// workaround because single-select select2 changing does not trigger
                        // ng-change (and so does not update ng-model either)
                        if (!$(this).prop("multiple")) {
                            $(this).on("select2:select", function (event) {
                                var id                   = event.params.data.id;
                                var label                = event.params.data.text;
                                var tile_option          = ctrl.tile.options[$(this).attr("name")];
                                var select_option_exists = tile_option.options.filter(function (opt) {
                                    return opt[0] === id;
                                }).length > 0;

                                tile_option.value = id;

                                // necessary step for AJAX selects: we create the option to be selected
                                if (!select_option_exists)
                                    tile_option.options.push([id, label]);

                                ctrl.onChange(tile_option);
                            });
                        }

						// Select2 will apply a width of 0 to the placeholder because the select is hidden when initialised
						$(this).parent().find('.select2-search__field').css('width', '');
					});
				}, 0);
			};

			$scope.select2ify();
		}


	}
}());
