/**
 * Amazon fulfillment metabox actions.
 */
(function ($) {
	'use strict';

	function getCommonPayload() {
		return {
			action: 'momcs_retry_amazon_fulfillment',
			order_id: $('#momcs-fulfillment-order-id').val(),
			nonce: $('#momcs-fulfillment-retry-nonce').val()
		};
	}

	function setMessage(type, message) {
		const $box = $('.momcs-fulfillment-message');
		$box.removeClass('error success').addClass(type).text(message).show();
	}

	function runRetry(channelUuid) {
		const payload = getCommonPayload();
		if (channelUuid) {
			payload.channel_uuid = channelUuid;
		}

		$('.momcs-fulfillment-actions .spinner').addClass('is-active');
		$('.momcs-fulfillment-retry-channel, .momcs-fulfillment-retry-all').prop('disabled', true);

		$.post(momcsFulfillmentStatus.ajaxUrl, payload)
			.done(function (response) {
				if (response && response.success) {
					setMessage('success', response.data && response.data.message ? response.data.message : momcsFulfillmentStatus.strings.retryQueued);
					window.setTimeout(function () {
						window.location.reload();
					}, 1200);
					return;
				}

				setMessage('error', response && response.data && response.data.message ? response.data.message : momcsFulfillmentStatus.strings.retryFailed);
			})
			.fail(function () {
				setMessage('error', momcsFulfillmentStatus.strings.retryFailed);
			})
			.always(function () {
				$('.momcs-fulfillment-actions .spinner').removeClass('is-active');
				$('.momcs-fulfillment-retry-channel, .momcs-fulfillment-retry-all').prop('disabled', false);
			});
	}

	$(document).on('click', '.momcs-fulfillment-retry-channel', function () {
		const channelUuid = $(this).data('channel-uuid') || '';
		runRetry(channelUuid);
	});

	$(document).on('click', '.momcs-fulfillment-retry-all', function () {
		runRetry('');
	});
})(jQuery);

