const dataExportForm = ( form ) => {

	if ( ! form ) {
		return;
	}

	const selectConditions = form.querySelectorAll('fieldset [data-selection-conditions]');
	if ( selectConditions && 0 !== selectConditions.length ) {
		// Handle dropdown changes, toggling additional conditions within contained <fieldset>
		selectConditions.forEach( dropdown => {
			dropdown.addEventListener( 'change', function() {
				const fieldset = dropdown.closest('fieldset');
				const selectCondition = dropdown.value;

				const conditions = fieldset.querySelectorAll('[data-selection-condition]');
				if ( 0 !== conditions.length ) {
					// Get all the data dependant conditions for the primary dropdown
					conditions.forEach( container => {
						const condition = container.getAttribute( 'data-selection-condition' );
						// If the container has the same value as the dropdown then mark it not hidden.
						const hideCondition = ( condition !== selectCondition );
						container.hidden = hideCondition;

						if ( hideCondition ) {
							// When hiding any condition containers, reset any <auto-complete> elements.
							const autocompletes = container.querySelectorAll('auto-complete');
							autocompletes.forEach( autocomplete => {
								autocomplete.resetAll();
							});
						}
					} );
				}
			});
		} );
	}

	// Handle post-export auto-download via data attribute
	const downloadRequestsTable = document.querySelector('form[data-pwp-exports] table.export_requests');
	if ( downloadRequestsTable ) {
		downloadRequestsTable.addEventListener( 'click', function(e) {
			let button = e.target.closest('button');
			if ( ! button )
				return;

			const requestID = button.getAttribute( 'data-pwp-export-download' );
			if ( ! requestID )
				return;

			const nonce = button.getAttribute( 'data-pwp-nonce' );
			if ( ! nonce )
				return;

			// Mark that we've started compiling the data
			button.setAttribute( 'hidden', '' );

			const $rowActions  = button.closest('.row-actions');
			const $progressing = button.closest('.download').querySelector('.export-processing');
			const $progress    = button.closest('.download').querySelector('.export-progress');
			const $notice      = button.closest('.download').querySelector('.notice');

			$rowActions.classList.add('processing');
			$progressing.removeAttribute( 'hidden' );

			let pageIndex = 1;

			function setExportProgress( pageIndex, totalPages ) {
				var progress       = ( totalPages > 0 ? pageIndex / totalPages : 0 ),
					progressString = Math.round( progress * 100 ).toString() + '%';

				$progress.textContent = progressString;
			}

			// Loop calls to sendAjax()
			const doNextExport = function( pageIndex ) {
				let params = new URLSearchParams();
				params.append( 'id', parseInt( requestID ) );
				params.append( 'page', pageIndex );
				params.append( 'action', 'pwp_export_data' );
				params.append( 'security', nonce );

				fetch(pwpSettings.url, {
					method: "POST",
					headers: {
						'Accept': 'application/json, */*;q=0.1',
						'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8',
						'X-Requested-With': 'XMLHttpRequest',
					},
					// Set the FormData instance as the request body
					body: params.toString(),
				}).then((response) => {
					if (!response.ok) {
						// Something when wrong
						console.log( response );
						throw new Error( 'Bad request' );
					}
					return response.json();
				}).then((response) => {
					let responseData = response.data;
					if ( ! responseData.done ) {
						setExportProgress( pageIndex, responseData.total );
						setTimeout( doNextExport( pageIndex + 1 ) );
					} else {
						// All done, show download
						$notice.removeAttribute( 'hidden' );
						$progressing.setAttribute('hidden', '');

						if ( responseData.download ) {
							const iframe = document.createElement('iframe');
							iframe.style.display = 'none';
							iframe.title = 'pwp-export-download';
							iframe.src = responseData.download;
							document.body.appendChild(iframe);
						}
					}
				});
			}
			// Let's begin
			doNextExport( pageIndex );
		});
	}
};

export default dataExportForm;
