/** @file
 * implementor's API for stats_tree
 * 2005, Luis E. G. Ontanon
 *
 * Wireshark - Network traffic analyzer
 * By Gerald Combs <gerald@wireshark.org>
 * Copyright 1998 Gerald Combs
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */
#pragma once
#include "stats_tree.h"
#include "ws_symbol_export.h"

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

#define INDENT_MAX 32
#define NUM_BUF_SIZE 32

/** implementations should define this to contain its own node related data
 * as well as some operations on it */
typedef struct _st_node_pres st_node_pres;

/** implementations should define this to contain its own dynamic tree related data
* as well as some operations on it */
typedef struct _tree_pres tree_pres;

/** implementations should define this to contain its own static tree related data
* as well as some operations on it */
typedef struct _tree_cfg_pres tree_cfg_pres;


typedef struct _stat_node stat_node;
typedef struct _stats_tree_cfg stats_tree_cfg;

typedef struct _range_pair {
	int floor;
	int ceil;
} range_pair_t;

typedef struct _burst_bucket burst_bucket;
struct _burst_bucket {
	burst_bucket	*next;
	burst_bucket	*prev;
	int			count;
	double			bucket_no;
	double			start_time;
};

/**
 * @brief Represents a node in a hierarchical statistics tree.
 *
 * Each node tracks statistical data such as counters, totals, min/max values,
 * and burst rates. Nodes may have children and siblings, forming a tree structure
 * used for organizing and displaying protocol or performance statistics.
 */
struct _stat_node {
	char* name;                     /**< Name of the statistic node. */
	int id;                         /**< Unique identifier for the node. */
	stat_node_datatype datatype;    /**< Type of data tracked (e.g., integer, float). */

	/** Counter value maintained by the node. */
	int counter;

	/** Total of all submitted values, used for computing averages. */
	union {
		int64_t int_total;          /**< Total for integer values. */
		double float_total;         /**< Total for floating-point values. */
	} total;

	/** Minimum value observed. */
	union {
		int int_min;                /**< Minimum integer value. */
		float float_min;            /**< Minimum float value. */
	} minvalue;

	/** Maximum value observed. */
	union {
		int int_max;                /**< Maximum integer value. */
		float float_max;            /**< Maximum float value. */
	} maxvalue;

	int st_flags;                   /**< Flags controlling node behavior or display. */

	/** Burst rate tracking fields. */
	int bcount;                     /**< Burst count. */
	burst_bucket *bh;               /**< Head of burst bucket list. */
	burst_bucket *bt;               /**< Tail of burst bucket list. */
	int max_burst;                  /**< Maximum burst count observed. */
	double burst_time;              /**< Time span of the burst. */

	GHashTable *hash;               /**< Child nodes indexed by name. */

	stats_tree *st;                 /**< Pointer to the owning statistics tree. */

	/** Tree relationships. */
	stat_node *parent;              /**< Pointer to parent node. */
	stat_node *children;            /**< Pointer to first child node. */
	stat_node *next;                /**< Pointer to next sibling node. */

	range_pair_t *rng;              /**< Optional range constraint for value filtering. */

	st_node_pres *pr;               /**< Presentation metadata for display formatting. */
};

struct _stats_tree {
	/** the "class" from which it's derived */
	stats_tree_cfg		*cfg;

	char			*filter;

	/* times */
	double			start;
	double			elapsed;
	double			now;

	int				st_flags;
	int			num_columns;
	char			*display_name;

   /** used to lookup named parents:
	*    key: parent node name
	*  value: parent node
	*/
	GHashTable		*names;

   /** used for quicker lookups of parent nodes */
	GPtrArray		*parents;

	/**
	 *  tree representation
	 * 	to be defined (if needed) by the implementations
	 */
	tree_pres		*pr;

	/** every tree in nature has one */
	stat_node		root;
};

struct _stats_tree_cfg {
	char			*abbr;
	char			*path;
	char			*title;
	char			*tapname;
	char			*first_column_name;
	register_stat_group_t	stat_group;

	bool plugin;

	/** dissector defined callbacks */
	stat_tree_packet_cb packet;
	stat_tree_init_cb init;
	stat_tree_cleanup_cb cleanup;

	/** tap listener flags for the per-packet callback */
	unsigned flags;

	/*
	 * node presentation callbacks
	 */

	/** last to be called at node creation */
	void (*setup_node_pr)(stat_node*);

	/**
	 * tree presentation callbacks
	 */
	tree_cfg_pres *pr;


	tree_pres *(*new_tree_pr)(stats_tree*);
	void (*free_tree_pr)(stats_tree*);

	/** flags for the stats tree (sorting etc.) default values to new trees */
	unsigned st_flags;
};

/* guess what, this is it! */
/**
 * @brief Registers callback functions for presenting statistics tree.
 *
 * @param registry_iterator Callback to iterate over the registry.
 * @param setup_node_pr Callback to set up a node in the statistics tree.
 * @param free_tree_pr Callback to free the statistics tree.
 * @param data User-defined data passed to callbacks.
 */
WS_DLL_PUBLIC void stats_tree_presentation(void (*registry_iterator)(void *,void *,void *),
				    void (*setup_node_pr)(stat_node*),
				    void (*free_tree_pr)(stats_tree*),
				    void *data);

/**
 * @brief Creates a new statistics tree.
 *
 * Initializes a new statistics tree with the given configuration and filter.
 *
 * @param cfg Pointer to the statistics tree configuration.
 * @param pr Pointer to the tree presentation structure.
 * @param filter The filter string for the statistics tree.
 * @return Pointer to the newly created statistics tree.
 */
WS_DLL_PUBLIC stats_tree *stats_tree_new(stats_tree_cfg *cfg, tree_pres *pr, const char *filter);

/** callback for taps */
WS_DLL_PUBLIC tap_packet_status stats_tree_packet(void*, packet_info*, epan_dissect_t*, const void *, tap_flags_t flags);

/** callback for reset */
WS_DLL_PUBLIC void stats_tree_reset(void *p_st);

/** callback for clear */
WS_DLL_PUBLIC void stats_tree_reinit(void *p_st);

/* callback for destroy */
/**
 * @brief Frees a stats_tree structure.
 *
 * @param st Pointer to the stats_tree structure to be freed.
 */
WS_DLL_PUBLIC void stats_tree_free(stats_tree *st);

/** given an ws_optarg splits the abbr part
   and returns a newly allocated buffer containing it */
WS_DLL_PUBLIC char *stats_tree_get_abbr(const char *ws_optarg);

/** obtains a stats tree from the registry given its abbr */
WS_DLL_PUBLIC stats_tree_cfg *stats_tree_get_cfg_by_abbr(const char *abbr);

/** obtains a stats tree list from the registry
    caller should free returned list with  g_list_free() */
WS_DLL_PUBLIC GList *stats_tree_get_cfg_list(void);

/** used to calculate the size of the indentation and the longest string */
WS_DLL_PUBLIC unsigned stats_tree_branch_max_namelen(const stat_node *node, unsigned indent);

/** a text representation of a node,
   if buffer is NULL returns a newly allocated string */
WS_DLL_PUBLIC char *stats_tree_node_to_str(const stat_node *node,
					char *buffer, unsigned len);

/** get the display name for the stats_tree (or node name) based on the
    st_sort_showfullname preference. If not set remove everything before
    last unescaped backslash. Caller must free the result */
WS_DLL_PUBLIC char* stats_tree_get_displayname (const char* fullname);

/** returns the column number of the default column to sort on */
WS_DLL_PUBLIC int stats_tree_get_default_sort_col (stats_tree *st);

/** returns the default sort order to use */
WS_DLL_PUBLIC bool stats_tree_is_default_sort_DESC (stats_tree *st);

/** returns the column name for a given column index */
WS_DLL_PUBLIC const char* stats_tree_get_column_name (stats_tree_cfg *st_config, int col_index);

/** returns the maximum number of characters in the value of a column */
WS_DLL_PUBLIC int stats_tree_get_column_size (int col_index);

/** returns the formatted column values for the current node
  as array of char*. Caller must free entries and free array */
WS_DLL_PUBLIC char** stats_tree_get_values_from_node (const stat_node* node);

/** function to compare two nodes for sort, based on sort_column. */
WS_DLL_PUBLIC int stats_tree_sort_compare (const stat_node *a,
					const stat_node *b,
					int sort_column,
					bool sort_descending);

/** wrapper for stats_tree_sort_compare() function that can be called from array sort. */
WS_DLL_PUBLIC int stat_node_array_sortcmp (const void *a,
					const void *b,
					void *user_data);

/** function to copy stats_tree into GString. format determines output format */
WS_DLL_PUBLIC GString* stats_tree_format_as_str(const stats_tree* st,
					st_format_type format_type,
					int sort_column,
					bool sort_descending);

/** helper funcation to add note to formatted stats_tree */
WS_DLL_PUBLIC void stats_tree_format_node_as_str(const stat_node *node,
					GString *s,
					st_format_type format_type,
					unsigned indent,
					const char *path,
					int maxnamelen,
					int sort_column,
					bool sort_descending);

#ifdef __cplusplus
}
#endif /* __cplusplus */
