const loadMoreVehiclesButton = jQuery( '.load-more-vehicles' );
let isLoading = false;

jQuery( document ).ready( function() {
	if ( loadMoreVehiclesButton.length && !isLoading ) {
		isLoading = true;

		jQuery( window ).on( 'scroll', function() {
			let top_of_element = loadMoreVehiclesButton.offset().top;
			let bottom_of_element = top_of_element + loadMoreVehiclesButton.outerHeight();
			let bottom_of_screen = jQuery( window).scrollTop() + jQuery( window ).innerHeight();
			let top_of_screen = jQuery( window ).scrollTop();

			if ( bottom_of_screen > top_of_element && top_of_screen < bottom_of_element )
				loadMoreVehicles();
		});

		jQuery( document ).on( 'click', '.load-more-vehicles', function( e ) {
			e.preventDefault();
			loadMoreVehicles();
		});
	}
});

function loadMoreVehicles() {
	jQuery( '#skeleton-container' ).show();

	let category = loadMoreVehiclesButton.data( 'category');
	let posts = loadMoreVehiclesButton.data( 'posts' );
	let page = loadMoreVehiclesButton.attr( 'data-page' );
	let limit = loadMoreVehiclesButton.data( 'limit' );
	let meta = loadMoreVehiclesButton.data( 'meta' );

	jQuery.ajax({
		type: 'POST',
		url: mobile_api_ajax.ajaxurl,
		data: {
			action: 'mobile_api_load_more_vehicles',
			mobile_api_nonce: mobile_api_ajax.nonce,
			category: category,
			posts: posts,
			page: page,
			limit: limit,
			meta: meta
		},
		success: function( data ) {
			loadMoreVehiclesButton.parent().prev().before( data );
			jQuery( '#skeleton-container' ).hide();

			page++;
			loadMoreVehiclesButton.attr( 'data-page', page );

			if ( page > limit )
				loadMoreVehiclesButton.hide();

			isLoading = false;
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			console.log( errorThrown );
			isLoading = false;
		}
	});
}

// Admin: Import vehicle
const ajaxContainer = jQuery( '#ajax[data-action="import-vehicles"]' );

jQuery( document ).ready( function() {
	const ajaxContainer = jQuery( '#ajax[data-action="import-vehicles"]' );
	if ( ajaxContainer.length > 0 ) {
		let total = ajaxContainer.data( 'total' );
		let limit = ajaxContainer.data( 'limit' );

		importVehiclesAJAX( 1, total, limit );
	}
});

function importVehiclesAJAX( page, total, limit ) {
	jQuery( '#ajax-progress output span' ).text( page );
	jQuery( '#ajax-progress progress' ).val( page );

	jQuery.ajax({
		type: 'POST',
		url: mobile_api_ajax.ajaxurl,
		data: {
			action: 'mobile_api_import_vehicles',
			mobile_api_nonce: mobile_api_ajax.nonce,

			page: page,
			total: total,
			limit: limit
		}, success: function( data, textStatus, XMLHttpRequest ) {
			ajaxContainer.html( data );

			if ( page < limit ) {
				page++;
				importVehiclesAJAX( page, total, limit );
			}
		}, error: function( XMLHttpRequest, textStatus, errorThrown ) {
			console.log( errorThrown );
		}
	});
}