/**
 * AJAX helper.
 *
 * @package northmill-online-shared
 */

/* global northmill_online_shared_ajax */
// noinspection JSUnusedGlobalSymbols Used in other files.
/**
 * AJAX helper.
 */
class NMS_AJAX {
	static post(
		ajax_opts,
		data,
		callback = this.success_silent,
		error_callback = this.fail_log,
		callback_data = null
	) {
		data[ 'action' ]                  = ajax_opts.action;
		data[ ajax_opts.nonce_query_arg ] = ajax_opts.nonce;

		jQuery.ajax(
			{
				url: northmill_online_shared_ajax.ajaxurl,
				type: 'POST',
				data,
				success: function ( response, textStatus, jqXHR ) {
					if ( response.success ) {
						callback( response, callback_data );
					} else {
						console.error( 'Application error:', response );
						error_callback( jqXHR, callback_data );
					}
				},
				error: function ( jqXHR ) {
					console.error( 'HTTP error:', jqXHR.status, jqXHR.statusText );
					error_callback( jqXHR, callback_data );
				},
			}
		);
	}

	static success_silent() {}

	static success_alert() {
		alert( northmill_online_shared_ajax.l10n.done );
	}

	static success_reload() {
		this.success_alert();
		location.reload();
	}

	static fail_alert( response ) {
		alert( northmill_online_shared_ajax.l10n.error + ': ' + response.responseJSON.data );
	}

	static fail_log( response ) {
		console.error( 'Error message: ' + response.responseJSON.data );
	}
}
