<?php
/**
 * Plugin Name: Heartbeat API test plugin
 * Description: For testing the heartbeat API only, not suitable for production sites. Updates the comments count on the dashboard.
 */


add_filter( 'heartbeat_send', 'heartbeat_test_comments_count', 10, 2 );

function heartbeat_test_comments_count($data, $screen_id) {
	// Check if we are on the right screen
	if ( $screen_id != 'dashboard' )
		return $data;

	$num_comments = wp_count_comments();

	// Add data in an unique array key.
	// The uniqueness requirement is the same like for PHP function names used in a plugin.
	$data['my-comments-count'] = array(
		'total-count' => number_format_i18n($num_comments->total_comments),
		'approved-count' => number_format_i18n($num_comments->approved),
		'pending-count' => number_format_i18n($num_comments->moderated),
		'spam-count' => number_format_i18n($num_comments->spam),
	);

	return $data;
}

add_action( 'admin_enqueue_scripts', 'heartbeat_test_enqueue' );

function heartbeat_test_enqueue($hook_suffix) {
	// Load scripts only where needed.
	if ( 'index.php' != $hook_suffix )
		return;

	// Make sure the JS part of the Heartbeat API is loaded.
	wp_enqueue_script('heartbeat');

	// Output the test JS.
	add_action( 'admin_print_footer_scripts', 'heartbeat_test_js', 20 );
}


function heartbeat_test_js() {
	?>
	<script>

	jQuery(document).ready( function($) {
		// Listen for the custom event "heartbeat-tick" on $(document).
		// Note: the event may change!
		// Always a good idea to add namespace.
		$(document).on( 'heartbeat-tick.comments-count', function(e, data) {
			//console.log(data);	// Uncomment to debug. Added by Jason Coleman 08AUG13
			
			if ( !data['my-comments-count'] )
				return;

			$.each( data['my-comments-count'], function(key, value) {
				var node = $('#dashboard_right_now .' + key);
				// Update only when changed
				if ( node.html() != value )
					node.html(value);
			});

			if ( typeof console != 'undefined' ) {
				// Show debug info
				wp.heartbeat.debug = true;
			}
				
		});
		
		// You need to send some information or the heartbeat won't tick back
		// Added by Jason Coleman 08AUG13
		$(document).on('heartbeat-send', function(e, data) {
			//console.log('Sending data to server.');	//uncomment to debug
			data['anything'] = 'anything';	//need some data to kick off AJAX call
		});
	});

	</script>
	<?php
}
