/*
 * Implementation of ExEzButton.h
 *
 * Erstellt:	05.01.2021
 * Autor: 		Flo Smilari
 */

#include "ExEzButton.h"

ExEzButton::ExEzButton(int pin) :
		ExEzButton(pin, false) {
}

ExEzButton::ExEzButton(int pin, bool _inverted) :
		ExEzButton(pin, _inverted, 2000) {
}

ExEzButton::ExEzButton(int pin, bool _inverted, int _longpressTime) :
		ezButton(pin) {
	inverted = _inverted;
	longpressTime = _longpressTime;
	pressedTime = 0;
	releasedTime = 0;
}

void ExEzButton::loop(void) {
	int lastSteadyStateBefore = getState();
	ezButton::loop();
	int lastSteadyStateAfter = ezButton::getState();
	if (lastSteadyStateBefore != lastSteadyStateAfter) {
		if (!inverted) {
			if (lastSteadyStateBefore == LOW && lastSteadyStateAfter == HIGH) {
				pressedTime = millis();
				releasedTime = 0;
			} else if (lastSteadyStateBefore == HIGH && lastSteadyStateAfter == LOW) {
				releasedTime = millis();
			}
		} else {
			if (lastSteadyStateBefore == HIGH && lastSteadyStateAfter == LOW) {
				pressedTime = millis();
				releasedTime = 0;
			} else if (lastSteadyStateBefore == LOW && lastSteadyStateAfter == HIGH) {
				releasedTime = millis();
			}
		}
	}
}

bool ExEzButton::isPressed() {
	bool pressed;
	if (!inverted) {
		pressed = ezButton::isPressed();
	} else {
		pressed = (ezButton::getPreviousState() == LOW && ezButton::getState() == HIGH);
	}
	return (pressed && pressedTime > 0 && releasedTime > 0 && (releasedTime - pressedTime) < longpressTime);
}

bool ExEzButton::isLongPressed() {
	if (releasedTime != 0) {
		unsigned long long pressDuration = releasedTime - pressedTime;
		bool longPressed = (pressDuration > longpressTime);
		if (longPressed) {
			pressedTime = 0;
			releasedTime = 0;
		}
		return longPressed;
	}
	return false;
}

bool ExEzButton::isPressing() {
	return ezButton::getState() == HIGH;
}

