/** Decimate hook.
 *
 * @author Steffen Vogel <stvogel@eonerc.rwth-aachen.de>
 * @copyright 2014-2019, Institute for Automation of Complex Power Systems, EONERC
 * @license GNU General Public License (version 3)
 *
 * VILLASnode
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *********************************************************************************/

/** @addtogroup hooks Hook functions
 * @{
 */

#include <villas/hook.h>
#include <villas/plugin.h>

struct decimate {
	int ratio;
	unsigned counter;
};

int decimate_set_ratio(struct hook *h, int ratio)
{
	struct decimate *p = (struct decimate *) h->_vd;

	p->ratio = ratio;

	return 0;
}

static int decimate_init(struct hook *h)
{
	struct decimate *p = (struct decimate *) h->_vd;

	p->counter = 0;

	return 0;
}

static int decimate_parse(struct hook *h, json_t *cfg)
{
	struct decimate *p = (struct decimate *) h->_vd;

	int ret;
	json_error_t err;

	ret = json_unpack_ex(cfg, &err, 0, "{ s: i }",
		"ratio", &p->ratio
	);
	if (ret)
		jerror(&err, "Failed to parse configuration of hook '%s'", hook_type_name(h->_vt));

	return 0;
}

static int decimate_process(struct hook *h, struct sample *smp)
{
	struct decimate *p = (struct decimate *) h->_vd;

	if (p->ratio && p->counter++ % p->ratio != 0)
		return HOOK_SKIP_SAMPLE;

	return HOOK_OK;
}

static struct plugin p = {
	.name		= "decimate",
	.description	= "Downsamping by integer factor",
	.type		= PLUGIN_TYPE_HOOK,
	.hook		= {
		.flags		= HOOK_NODE_READ | HOOK_NODE_WRITE | HOOK_PATH,
		.priority	= 99,
		.init		= decimate_init,
		.parse		= decimate_parse,
		.process	= decimate_process,
		.size		= sizeof(struct decimate)
	}
};

REGISTER_PLUGIN(&p)

/** @} */