#include "shark_xl.h"
#include "common.h"
#include "app_end_ctr.h"

shark_u16 shark_xl_ticks;
shark_u8 shark_xl_skip;

shark_u16 shark_xl_speed_max;
shark_u16 shark_xl_speed_tmp;
shark_u16 shark_xl_speed;

shark_u8 shark_xl_detected;

void shark_xl_init(void)
{
	rcu_periph_clock_enable(GPIO_RCU_XL);
	gpio_init(GPIO_PORT_XL, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, GPIO_PIN_XL);

	gpio_exti_source_select(EXTI_PORT_XL, EXTI_PIN_XL);
	exti_init(EXTI_XL, EXTI_INTERRUPT, EXTI_TRIG_FALLING);
	exti_interrupt_flag_clear(EXTI_XL);
}

void shark_xl_tick(void)
{
	if (shark_xl_ticks < CONFIG_XL_TICKS) {
		shark_xl_ticks++;

		if (gpio_input_bit_get(GPIO_PORT_XL, GPIO_PIN_XL) == RESET) {
			shark_xl_speed_tmp++;
		}
	} else {
		shark_bool state;

		shark_xl_ticks = 0;

		if (shark_xl_skip > 0) {
			shark_xl_skip--;
			shark_xl_speed = 0;
		} else {
			shark_xl_speed = shark_xl_speed_tmp;
		}

		state = (shark_xl_speed > CONFIG_XL_MIN);
		end_ctr_self_ss_new.xl_sta = state;

		if (state) {
			shark_xl_detected = SHARK_XL_DEBOUNCE;
		} else if (shark_xl_detected > 0) {
			shark_xl_detected--;
		}

		if (shark_xl_speed_max < shark_xl_speed) {
			shark_xl_speed_max = shark_xl_speed;
		}

		shark_xl_speed_tmp = 0;
		exti_interrupt_enable(EXTI_XL);
	}
}

void shark_xl_isr(void)
{
	if (++shark_xl_speed_tmp > CONFIG_XL_MAX) {
		exti_interrupt_disable(EXTI_XL);
	}
}
