{% import 'ef_macros.html' as ef_macros %}

{% macro search_button() %}
	<button id="{{ field.id }}-search-button" class="{{ field.button_class }}">
		{{ field.button_text }}
	</button>
{% endmacro %}

<div {{ field.form_group_attributes }}>
	{{ ef_macros.standard_label(field) }}

	<div {{ field.input_column_attributes }}>
		{% if field.style == styles.BOOTSTRAP_4 %}<div>{% endif %}

    	<input type="{{ field.type }}"
		       class="{{ field.input_classes }}"
		       name="{{ field.name }}"
		       id="{{ field.id }}" value="{{ field.value|sn }}" placeholder="{{ field.placeholder|sn }}"
		       {% if field.readonly %}readonly{% endif %}>

		{% if field.inline_button %}
			{{ search_button() }}
		{% endif %}

		{% if field.style == styles.BOOTSTRAP_4 %}</div>{% endif %}
		{{ ef_macros.bs4_error(field) }}
		{{ ef_macros.bs4_help_text(field) }}
	</div>

	{{ ef_macros.bs3_error(field) }}
	{{ ef_macros.bs3_help_text(field) }}

	<div class="{{ field.error_column_class }}" id="{{ field.id }}-ajax-error" style="display: none;">
		{% if field.style == styles.BOOTSTRAP_3 %}
			<p class="help-block">
				{# This invisible label pushed the validation message to be in line with the input #}
				{% if field.form.form_type == formtype.INLINE %}
					<span style="visibility: hidden">
						{{ ef_macros.standard_label(field) }}
					</span>
				{% endif %}
				<span class="error-content">
				</span>
			</p>
		{% elif field.style == styles.BOOTSTRAP_4 %}
			{# this is a hack for bootstrap 4 #}
			<span class="form-control is-invalid" style="display: none;"></span>
			<p class="invalid-feedback">
			</p>
		{% endif %}
	</div>

</div>

{% if not field.inline_button %}
	<div {{ field.form_group_attributes }}>
		<div {{ field.input_column_no_label_attributes }}>
			{{ search_button() }}
		</div>
	</div>
{% endif %}

<div id="{{ field.id }}-result-group" class="getaddress-result-group" style="display: none;">
	<div {{ field.form_group_attributes }}>
		<div {{ field.input_column_no_label_attributes }}>
			<select class="form-control" id="{{ field.id }}-result-select">
			
			</select>
		</div>
	</div>
</div>


<script>
	$(document).ready(function() {
		var errors = {
			404: 'No addresses could be found for this postcode',
			400: 'The postcode you entered is not valid',
			401: 'Invalid API key',
			429: 'This service has run out of available requests - try again tomorrow',
			500: 'Your request could not be processed due to an error in the postcode lookup service'
		};

		var apiEndpoint = "https://api.getAddress.io/find";
		var field = $("#{{ field.id }}");
		var button = $("#{{ field.id }}-search-button");
		var apiKey = "{{ field.api_key }}";
		var lastSearch = null;
		var resultGroup = $("#{{ field.id }}-result-group");
		var resultSelect = $("#{{ field.id }}-result-select");
		var buttonText = "{{ field.button_text }}";
		var errorDiv = $("#{{ field.id }}-ajax-error");
		var formGroup = field.closest('.form-group');
		var sortAddresses = {{ 'true' if field.sort_addresses else 'false' }};
		
		{% if field.line1_id %}
			var line1Input = $("#{{ field.line1_id }}");
		{% else %}
			var line1Input = null;
		{% endif %}
		
		{% if field.line2_id %}
			var line2Input = $("#{{ field.line2_id }}");
		{% else %}
			var line2Input = null;
		{% endif %}
		
		{% if field.line3_id %}
			var line3Input = $("#{{ field.line3_id }}");
		{% else %}
			var line3Input = null;
		{% endif %}
		
		{% if field.town_id %}
			var townInput = $("#{{ field.town_id }}");
		{% else %}
			var townInput = null;
		{% endif %}
		
		{% if field.county_id %}
			var countyInput = $("#{{ field.county_id }}");
		{% else %}
			var countyInput = null;
		{% endif %}
		
		var setError = function(error) {
			formGroup.addClass('has-error');
			errorDiv.find('p').text(error);
			errorDiv.show();
		};

		var clearError = function() {
			errorDiv.hide();
			formGroup.removeClass('has-error');
		}

		var lookupAddress = function() {
			var postcode = field.val();

			if (postcode.trim() == "") {
				setError('Please enter a postcode');
				return false;
			}
			
			// don't allow multiple searches for the same thing
			if (postcode == lastSearch) {
				return false;
			}
			lastSearch = postcode;
			
			button.text('Searching...');
			button.prop('disabled', true);
			resultGroup.hide();
			clearError();

			var url = apiEndpoint + '/' + postcode;
			var data = {
				'api-key': apiKey,
				'format': true,
				'sort': sortAddresses
			};

			$.ajax({
				url: url,
				data: data,
				success: handleLookupAddress,
				error: handleLookupAddressError,
				dataType: 'json'
			});

			return false;
		};

		var handleLookupAddressError = function(result) {
			button.prop('disabled', false);
			button.text(buttonText);

			var statusCode = result.status;
			var error = 'Something went wrong!';
			if (typeof errors[statusCode] !== 'undefined') {
				error = errors[statusCode];
			}

			setError(error);
		};

		var handleLookupAddress = function(result) {
			button.prop('disabled', false);
			button.text(buttonText);

			resultSelect.html('');
			resultSelect.append($("<option>Select an address</option>"));

			for (var i=0; i<result.addresses.length; i++ ) {
				var address = result.addresses[i];
				var option = $("<option>");
				var label = '';
				for (var j=0; j<address.length; j++) {
					var part = address[j];
					if (part) {
						if (label) {
							label += ', ';
						}
						label += part;
					}
				}
				option.text(label);
				option.data('line1', address[0]);
				option.data('line2', address[1]);
				option.data('line3', address[2]);
				option.data('town', address[3]);
				option.data('county', address[4]);

				resultSelect.append(option);
			}
			resultGroup.show();
		};

		var handleAddressSelect = function(event) {
			var option = resultSelect.find(":checked");
			if (option.data('line1')) {
				// This was an address
				if (line1Input) {
					line1Input.val(option.data('line1'));
				}
				if (line2Input) {
					line2Input.val(option.data('line2'));
				}
				if (line3Input) {
					line3Input.val(option.data('line3'));
				}
				if (townInput) {
					townInput.val(option.data('town'));
				}
				if (countyInput) {
					countyInput.val(option.data('county'));
				}
			}
		};

		button.click(lookupAddress);
		resultSelect.change(handleAddressSelect);
	});
</script>
