import $ from 'jquery';

/**
 * Retrieves updated product dimensions from a table.
 *
 * @param {JQuery} table - The table element.
 * @returns {ProductDimensionsData[]} An array of updated product dimensions.
 */
export const get_updated_dimensions = ( table: JQuery ): ProductDimensionsData[] => {
	const updated_dimensions: ProductDimensionsData[] = [];

	if ( table.length ) {
		table.find( 'tbody .table-row--first' ).each( ( _index, row ) => {
			const product_id = $( row ).data( 'product_id' );

			if ( typeof product_id === 'undefined' ) {
				return;
			}

			const product_name = $( row ).data( 'product_name' );
			const quantity_element = $( `#${ product_id }-quantity` );

			let quantity: number = 1;

			if ( quantity_element && quantity_element.length ) {
				quantity = parseInt( quantity_element.val() as string );
			}

			quantity = isNaN( quantity ) ? 1 : quantity

			const dimensions_data: ProductDimensionsData = {
				product_id,
				product_name,
				skip_row: Boolean( $( `#${ product_id }-skip` ).prop( 'checked' ) ),
				weight: $( `#${ product_id }-weight` ).val()?.toString() ?? '',
				length: $( `#${ product_id }-length` ).val()?.toString() ?? '',
				height: $( `#${ product_id }-height` ).val()?.toString() ?? '',
				width: $( `#${ product_id }-width` ).val()?.toString() ?? '',
				quantity,
			};

			updated_dimensions.push( dimensions_data );
		} );
	}

	return updated_dimensions;
};

