import ClickEvent = JQuery.ClickEvent;
import { check_license_key } from './license_key/check_license_key';
import $ from 'jquery';
import { reset_all_variables } from './reset_all_variables';
import { show_pdf_from_response } from './show_pdf_from_response';
import { send_get_shipping_label_request } from './send_get_shipping_label_request';

export const print_shipping_label_by_id = async (event: ClickEvent) => {
	event.preventDefault();

	const license_is_ok = check_license_key();

	if ( !license_is_ok ) {
		console.error( 'License key is not set' );
		return;
	}

	const _this = event.currentTarget;
	const order_id: string = $( _this ).data( 'order-id' );
	const label_id = $( _this ).data( 'id' );

	const response = await send_get_shipping_label_request( order_id, true, label_id );

	if ( !response ) {
		console.error( 'No Existing shipping label response' );
		reset_all_variables( order_id );
		return;
	}

	if ( response.error ) {
		let error_text = 'Some kind of error occurred on the server when processing the API request.';

		if ( response.message ) {
			error_text += ' Existing Shipping label response error: ' + response.message;
		}

		console.error( error_text );

		alert( error_text );
		reset_all_variables( order_id );
		return;
	}

	show_pdf_from_response( response );
	reset_all_variables( order_id );
	return;
}
