/* gkrelltopd.c	- requires GKrellM 2.2.0 or better
*/

#include <gkrellm2/gkrellmd.h>

#include "gkrelltop.h"



/* Duplicate the local data collection that is in gkrelltop.c
*/
static struct process	best[MAXITEMS];
static gint				ntop;


static void
gkrelltopd_update(GkrellmdMonitor *mon, gboolean first_update)
	{
	struct process	*curbest[MAXITEMS] = { 0, 0, 0 };
	int				n, i;
	gboolean		any_changed;

	if (!GK.second_tick && !first_update)
		return;

	if ((n = gkrelltop_process_find_top_three(curbest)) <= 0)
		return;

	any_changed = FALSE;

	for (i = 0; i < n; ++i)
		{
		best[i].changed = gkrellmd_dup_string(&best[i].name, curbest[i]->name);
		any_changed |= best[i].changed;
		if (   best[i].amount != curbest[i]->amount
			|| best[i].pid != curbest[i]->pid
		   )
			{
			best[i].amount = curbest[i]->amount;
			best[i].pid = curbest[i]->pid;
			best[i].changed = TRUE;
			any_changed = TRUE;
			}
		}
	if (n != ntop)
		any_changed = TRUE;
	ntop = n;
	if (any_changed)
		gkrellmd_need_serve(mon);
	}


  /* This function is called to collect data to be sent to clients.
  |  Send all data when first_serve is true, and only changed data at
  |  other times.
  */
static void
gkrelltopd_serve_data(GkrellmdMonitor *mon, gboolean first_serve)
	{
	gchar	buf[128];
	gint	i;

	gkrellmd_set_serve_name(mon, GKRELLTOP_SERVE_NAME);

	for (i = 0; i < ntop; ++i)
		{
		if (!best[i].changed && !first_serve)
			continue;
		snprintf(buf, sizeof(buf), "best %d %s %d %3.1f\n",
				i, best[i].name, best[i].pid, best[i].amount);
		gkrellmd_serve_data(mon, buf);
		}

	/* Just always send ntop.
	*/
	snprintf(buf, sizeof(buf), "ntop %d\n", ntop);
	gkrellmd_serve_data(mon, buf);
	}


static void
gkrelltopd_serve_setup(GkrellmdMonitor *mon)
	{
	gchar	buf[32];

	/* Just in case a future gkrelltop version will need to know...
	*/
	snprintf(buf, sizeof(buf), "version %d %d %d",
			GKRELLTOP_VERSION_MAJOR,
			GKRELLTOP_VERSION_MINOR,
			GKRELLTOP_VERSION_REV);

	gkrellmd_plugin_serve_setup(mon, GKRELLTOP_SERVE_NAME, buf);
	}


static GkrellmdMonitor	gkrelltop_monitor =
	{
	GKRELLTOP_SERVE_NAME,
	gkrelltopd_update,
	gkrelltopd_serve_data,
	gkrelltopd_serve_setup,
	};


GkrellmdMonitor *
gkrellmd_init_plugin(void)
	{
	return &gkrelltop_monitor;
	}
