#include "Buzzer.h"
#include "util/delay.h"

#include <avr/interrupt.h>
#include <avr/io.h>

#define BEEP_TOGGLES 2000

volatile uint16_t toggle_count = 0;
volatile uint8_t buzzer_active = 0;

const uint16_t notes[] = {
    659, 784, 988, 1319, 0,
};

const uint16_t durations[] = {
    120, 120, 120, 250, 80,
};

#define SONG_LEN 5

void init_buzzer() {
    DDRB |= (1 << PB6);

    TCCR1A = 0;
    TCCR1B = (1 << WGM12);

    TCCR1B |= (1 << CS11);

    OCR1A = 999;

    TIMSK1 |= (1 << OCIE1A);
}

void play_buzzer() {
    for (int i = 0; i < SONG_LEN; i++) {
        if (notes[i] == 0) {
            buzzer_active = 0;
            PORTB &= ~(1 << PB6);
        } else {
            OCR1A = (F_CPU / 8UL) / (2UL * notes[i]) - 1;
            buzzer_active = 1;
        }

        for (uint16_t j = 0; j < durations[i]; j++) {
            _delay_ms(1);
        }
    }

    buzzer_active = 0;
    PORTB &= ~(1 << PB6);
}

ISR(TIMER1_COMPA_vect) {
    if (buzzer_active) {
        PORTB ^= (1 << PB6);
    }
}
