#include "rotary_encoder.hpp"

int RotaryEncoder::value_select(Display &display) {
	int seconds{0};

	while (analogRead(0) > 950) {
		int newEncVal{_encoder.read()};

		if (newEncVal != _currentValue) {
			int increment{0};
			_shift += newEncVal - _currentValue;
			_currentValue = newEncVal;

			if (-4 >= _shift || _shift >= 4) {
				/* todo make real comp : int size is target dependant */
				int sign = _shift >> 2;

				if (seconds < 60) {
					increment = 1 * sign;

					if (seconds + increment < 0) {
						seconds = 5940;
						increment = 0;
					} else if (seconds + increment >= 60) {
						seconds = 60;
						increment = 0;
					}
				} else if (seconds < 600) {
					increment = sign * 10;

					if (seconds + increment < 60) {
						seconds = 59;
						increment = 0;
					} else if (seconds + increment > 590) {
						seconds = 600;
						increment = 0;
					}
				} else {
					increment = sign * 60;

					if (seconds + increment < 600) {
						seconds = 590;
						increment = 0;
					} else if (seconds + increment > 5940) {
						seconds = 0;
						increment = 0;
					}
				}

				seconds += increment;

				display.print_time(seconds);

				_shift = 0;
			}
		}
	}

	return seconds;
}
