#include "Keyboard.h"
#include "HID.h"

#if F_CPU == 16000000
#error should be running at 8MHz
#endif

#define PIN A0

void goto_bootloader() {
    cli();
    UDCON |= (1<<DETACH);
    USBCON |= (1<<USBE);

    TIMSK0 = 0;

    MCUCR |= (1<<IVCE);
    MCUCR |= (1<<IVSEL);
    sei();
    asm("jmp 0x7000");
}
    

void check_blcmd() {
    if (Serial.available()) {
        String in = Serial.readStringUntil("\n");
        if (in.equals("bootloader\n")) {
            goto_bootloader();
        }
    }
}

void toggle() {}

void turned_on() {
    Keyboard.press(KEY_F15);
    Keyboard.releaseAll();
}

void turned_off() {
    Keyboard.press(KEY_F14);
    Keyboard.releaseAll();
}

void setup() {
    pinMode(PIN, INPUT_PULLUP);
    Keyboard.begin();
    Serial.begin(9600);
    Serial.setTimeout(50);
}


void loop() {
    static bool last_state = 0;

    bool current_state = digitalRead(PIN);

    if (last_state != current_state) {
        toggle();
        if (current_state)
            turned_on();
        else
            turned_off();
        last_state = current_state;
    }


    check_blcmd();
    delay(100);

}
