#ifndef __taster_H__
#define __taster_H__
#include <Arduino.h>
#include <FunctionalInterrupt.h>

class taster
{
private:
    volatile const unsigned long _BOUNCING_TIME_MS = 300;
    volatile unsigned long _last_pressed;
    unsigned long _number_pressed;
    unsigned long _number_checked;
    size_t _taster_pin;
    volatile unsigned long * _ptr_number_pressed;

    void IRAM_ATTR _taster_int() 
    {
        unsigned long msecs = millis();
        if(msecs -_last_pressed > _BOUNCING_TIME_MS)
        {
            _last_pressed = msecs;
            _number_pressed += 1;
        }
    }

public:
    //taster(const size_t pin, volatile unsigned long* ptr_number_pressed);
    taster(const size_t pin);
    ~taster();
    bool pressed();
    void reset();
    void begin();
};

//taster::taster(size_t pin, volatile unsigned long* ptr_number_pressed)
taster::taster(size_t pin)
{
    _taster_pin = pin;
    //_ptr_number_pressed = ptr_number_pressed;
    _number_checked = 0;
    _number_pressed = 0;
    _last_pressed = 0;
}

void taster::begin()
{
    pinMode(_taster_pin, INPUT_PULLUP);
    attachInterrupt(_taster_pin, std::bind(&taster::_taster_int,this), FALLING);
    //attachInterrupt(_taster_pin,  isrfunction, FALLING);
}

taster::~taster()
{
    //detachInterrupt(_taster_pin);
}

bool taster::pressed() {
    //if (*_ptr_number_pressed > _number_checked) 
    if (_number_pressed > _number_checked) 
    {
        //_number_checked = *_ptr_number_pressed;
        _number_checked = _number_pressed;
        return true;
    }
    return false;
}

void taster::reset() {
    _number_pressed = _number_checked;
}

#endif