/**
 * DataStream settings page tooling.
 */
( function ( wp ) {
	'use strict';

	const apiFetch = wp.apiFetch;
	const config   = window.datastreamSettings || {};
	const labels   = config.labels || {};

	function setResult( message, isError ) {
		const el = document.getElementById( 'datastream-tool-result' );
		if ( ! el ) {
			return;
		}
		el.textContent = message;
		el.className = 'datastream-tool-result ' + ( isError ? 'is-error' : 'is-success' );
	}

	function setInlineTestResult( message, isError ) {
		const el = document.getElementById( 'datastream-test-result' );
		if ( ! el ) {
			return;
		}
		el.textContent = message;
		el.className = isError ? 'is-error' : 'is-success';
	}

	async function testConnection( useFormUrl ) {
		const urlInput = document.querySelector( '[name="datastream_api_url"]' );
		const body     = {};

		if ( useFormUrl && urlInput ) {
			body.url = urlInput.value;
		}

		setInlineTestResult( labels.testing || 'Testing…', false );
		setResult( labels.testing || 'Testing…', false );

		try {
			const result = await apiFetch( {
				path: '/datastream/v1/test-connection',
				method: 'POST',
				data: body,
			} );

			const msg = result.message
				+ ( result.item_count !== undefined ? ' (' + result.item_count + ' items, ' + result.duration_ms + 'ms)' : '' );

			setInlineTestResult( msg, ! result.success );
			setResult( msg, ! result.success );
		} catch ( error ) {
			const msg = labels.failed || 'Action failed.';
			setInlineTestResult( msg, true );
			setResult( msg, true );
			console.error( error );
		}
	}

	async function runTool( action ) {
		let data = {};

		if ( 'purge-all' === action ) {
			const confirmToken = window.prompt( labels.confirmPurge || 'Type DELETE to confirm.' );
			if ( 'DELETE' !== confirmToken ) {
				setResult( 'Cancelled.', false );
				return;
			}
			data.confirm = 'DELETE';
		}

		setResult( labels.working || 'Working…', false );

		try {
			if ( 'sync' === action ) {
				const result = await apiFetch( { path: '/datastream/v1/sync', method: 'POST' } );
				setResult( result.message || labels.done, ! result.success );
				return;
			}

			if ( 'test-connection' === action ) {
				await testConnection( true );
				return;
			}

			const result = await apiFetch( {
				path: '/datastream/v1/tools/' + action,
				method: 'POST',
				data: data,
			} );

			setResult( result.message || labels.done, ! result.success );
		} catch ( error ) {
			setResult( labels.failed || 'Action failed.', true );
			console.error( error );
		}
	}

	document.addEventListener( 'DOMContentLoaded', function () {
		const testBtn = document.getElementById( 'datastream-test-connection' );
		if ( testBtn ) {
			testBtn.addEventListener( 'click', function () {
				testConnection( true );
			} );
		}

		document.querySelectorAll( '[data-ds-tool]' ).forEach( function ( button ) {
			button.addEventListener( 'click', function () {
				runTool( button.getAttribute( 'data-ds-tool' ) );
			} );
		} );
	} );

} )( window.wp );
