#include <stdlib.h>
#include <tfe_fieldstat.h>

int tfe_fieldstat_metric_incrby(struct tfe_fieldstat_metric_t *fieldstat, unsigned int column_id, long long value, const struct fieldstat_tag tags[], int thread_id)
{
	return fieldstat_dynamic_table_metric_value_incrby(fieldstat->instance, fieldstat->table_id, column_id, "proxy_rule_hits", value, tags, (size_t)TAG_MAX, thread_id);
}

struct tfe_fieldstat_metric_t *tfe_fieldstat_metric_create(char *telegraf_ip, int telegraf_port, char *app_name, int cycle, int max_thread, void *local_logger)
{
	int i=0;

	struct fieldstat_tag metric_tags[TAG_MAX] = {{"vsys_id", 0, -1}, {"rule_id", 0, -1}, {"pinning_status", 0, -1 }, {"action", 0, -1}, {"sub_action", 2, -1} };
	const char *column_field[COLUMN_MAX] = {"hit_count", "in_bytes", "out_bytes", "in_pkts", "out_pkts"};
	enum field_type column_type[COLUMN_MAX] = {FIELD_TYPE_COUNTER, FIELD_TYPE_COUNTER, FIELD_TYPE_COUNTER, FIELD_TYPE_COUNTER, FIELD_TYPE_COUNTER};

	struct tfe_fieldstat_metric_t *fieldstat = ALLOC(struct tfe_fieldstat_metric_t, 1);

	fieldstat->instance = fieldstat_dynamic_instance_new(app_name, max_thread);
	if(!fieldstat->instance)
	{
		TFE_LOG_ERROR(local_logger, "fieldstat3 dynamic instance init failed.");
		return NULL;
	}

	fieldstat->max_thread=max_thread;
	fieldstat_dynamic_set_line_protocol_server(fieldstat->instance, telegraf_ip, telegraf_port);
	fieldstat_dynamic_set_output_interval(fieldstat->instance, cycle);

	fieldstat->table_id = fieldstat_register_dynamic_table(fieldstat->instance, "proxy_rule_hits", column_field, column_type, (size_t)COLUMN_MAX, fieldstat->column_array);
	if(fieldstat->table_id < 0)
	{
		TFE_LOG_ERROR(local_logger, "fieldstat3 register dynamic table failed.");
		FREE(&fieldstat);
		return NULL;
	}

	fieldstat->tags = ALLOC(struct fieldstat_tag*, max_thread);
	for (i = 0; i < max_thread; i++)
	{
		fieldstat->tags[i] = ALLOC(struct fieldstat_tag, TAG_MAX);
		memcpy(fieldstat->tags[i], metric_tags, sizeof(struct fieldstat_tag) * (size_t)TAG_MAX);
	}

	fieldstat_dynamic_instance_start(fieldstat->instance);
	return fieldstat;
}

void tfe_fieldstat_metric_destroy(struct tfe_fieldstat_metric_t *fieldstat)
{
	if(fieldstat)
	{
		if(fieldstat->instance)
		{
			fieldstat_dynamic_instance_free(fieldstat->instance);
		}

		for (int i = 0; i < fieldstat->max_thread; i++)
		{
			if (fieldstat->tags[i])
			{
				FREE(&fieldstat->tags[i]);
			}
		}
		FREE(&fieldstat->tags);
		FREE(&fieldstat);
	}
}

