/*
 * Copyright 2017-2024 Oleg Borodin <onborodin@gmail.com>
 */

#include <stdint.h>
#include <stdbool.h>

#include <avr/io.h>

#include <button.h>
#include <tool.h>

button_t button;

void button_init(void) {
    /* D3 PD3: Set key input */
    REG_SETDOWN_BIT(DDRD, PD3);
    REG_SETUP_BIT(PORTD, PD3);
}

bool button_is_pressed(void) {
    if (!REG_BIT_VALUE(PIND, PD3)) {
        return true;
    }
    return false;
}

uint8_t button_get(void) {
    if (button.strokes_ended) {
        uint8_t counter = button.push_counter;
        button.push_counter = 0;
        button.strokes_ended = false;
        return counter;
    }
    return 0;
}

void button_reset(void) {
    button.was_pressed = false;
    button.time_counter = 0;
    button.push_counter = 0;
    button.released_time = 0;
    button.strokes_ended = false;
}

#define BUTTON_TIME_PRESSED    20
#define BUTTON_TIME_RELEASED   20
#define BUTTON_RELEASED_TIME  300

void button_handle(void) {
    if (!button.strokes_ended) {
        if (!button.was_pressed) {
            if (button_is_pressed()) {
                button.time_counter++;
            }
            if (button.time_counter > BUTTON_TIME_PRESSED) {
                button.time_counter = 0;
                button.was_pressed = true;
                button.released_time = 0;
            }
        } else {
            if (!button_is_pressed()) {
                button.time_counter++;
            }
            if (button.time_counter > BUTTON_TIME_RELEASED) {
                button.push_counter++;
                button.time_counter = 0;
                button.was_pressed = false;
                button.released_time = 0;
            }
        }
        if (button.released_time++ > BUTTON_RELEASED_TIME) {
            button.strokes_ended = true;
            button.was_pressed = false;
            button.time_counter = 0;
            button.released_time = 0;
        }


    }
}

