/**** Includes ****/
#include "../utils/utils.h"
#include "handbrake.h"

using namespace dccd;

/**** Private definitions ****/
/**** Private constants ****/
/**** Private variables ****/
/**** Private function declarations ****/
/**** Public function definitions ****/
dccd::Handbrake::Handbrake(void)
{
	return;
}

dccd::Handbrake::~Handbrake(void)
{
	return;
}

void dccd::Handbrake::init(dccd::DccdHw* dccd_hw)
{	
	this->hardware = dccd_hw;
	this->latch_time = 0;
	this->hbrake_latch = 0;
	this->start_ts = 0;
	this->is_active = 0;
}

void dccd::Handbrake::cfg_debounce(uint16_t dbnc_time)
{
	this->hardware->handbrake.dbnc_lim = dbnc_time;
}

uint8_t dccd::Handbrake::process(void)
{
	uint16_t ts_now = this->hardware->counter.read();
	
	if(this->hardware->handbrake.state > 0)
	{
		if(this->hardware->handbrake.is_new)
		{
			this->hardware->handbrake.is_new = 0;
			// Note start time
			this->start_ts = ts_now;
			this->hbrake_latch = 1;
		};
		this->is_active = 1;
	}
	else if((this->hbrake_latch != 0)&&(this->latch_time != 0))
	{
		uint16_t td = util::time_delta(this->start_ts, ts_now);
		uint32_t td_ms = this->hardware->counter.convert_ms(td);
		if(td_ms >= this->latch_time)
		{
			this->hbrake_latch = 0;
			if(this->hardware->handbrake.state > 0) this->is_active = 1;
			else this->is_active = 0;
		};
	}
	else
	{
		this->is_active = 0;
	}
	
	return this->is_active;
}

/**** Private function definitions ***/
