#include "keypad.hpp"
#include "util/delay.h"
#include <avr/interrupt.h>
#include <avr/io.h>

volatile uint8_t sw = 0;

Keypad::Keypad() {
    pins[0] = PK0;
    pins[1] = PK1;
    pins[2] = PK2;
    pins[3] = PK3;

    DDRK &= ~((1 << PK0) | (1 << PK1) | (1 << PK2) | (1 << PK3));
    PORTK |= (1 << PK0) | (1 << PK1) | (1 << PK2) | (1 << PK3);

    PCICR |= (1 << PCIE2);
    PCMSK2 |= (1 << PCINT16) | (1 << PCINT17) | (1 << PCINT18) | (1 << PCINT19);
}

char Keypad::GetKey() {
    static uint8_t state = 255;

    if (!sw) {
        return 0;
    }

    _delay_ms(20);

    uint8_t curr = PINK;

    sw = 0;

    if ((state & (1 << PK0)) && !(curr & (1 << PK0))) {
        state = curr;
        return '3';
    }

    if ((state & (1 << PK1)) && !(curr & (1 << PK1))) {
        state = curr;
        return '4';
    }

    if ((state & (1 << PK2)) && !(curr & (1 << PK2))) {
        state = curr;
        return '1';
    }

    if ((state & (1 << PK3)) && !(curr & (1 << PK3))) {
        state = curr;
        return '2';
    }

    state = curr;

    return 0;
}

ISR(PCINT2_vect) { sw = 1; }
