#include <Arduino.h>
#line 1 "/Users/martinmusinka/Documents/Skola/Diplomova_Praca/Program/MidiSequencer/MidiSequencer.ino"
#include "SoftPWM.h"
#include "SoftPWM_timer.h"
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <MIDI.h>
#include "Rotary.h"
#include "display.h"
#include "stateMachine.h"


#line 13 "/Users/martinmusinka/Documents/Skola/Diplomova_Praca/Program/MidiSequencer/MidiSequencer.ino"
void MyHandleNoteOn(byte channel, byte pitch, byte velocity);
#line 33 "/Users/martinmusinka/Documents/Skola/Diplomova_Praca/Program/MidiSequencer/MidiSequencer.ino"
void MyHandleNoteOff(byte channel, byte pitch, byte velocity);
#line 48 "/Users/martinmusinka/Documents/Skola/Diplomova_Praca/Program/MidiSequencer/MidiSequencer.ino"
void setup();
#line 86 "/Users/martinmusinka/Documents/Skola/Diplomova_Praca/Program/MidiSequencer/MidiSequencer.ino"
void loop();
#line 13 "/Users/martinmusinka/Documents/Skola/Diplomova_Praca/Program/MidiSequencer/MidiSequencer.ino"
void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
  Serial.print("NoteOn ");
  Serial.print("Channel:  ");
  Serial.print(channel);
  Serial.print(", Pitch:  ");
  Serial.print(pitch,HEX);
  Serial.print(", Velocity:  ");
  Serial.print(velocity);
  Serial.print(", LED number:  ");
  Serial.println(pitch-0x30);

  counter++;
  
  digitalWrite(myPins[constrain(pitch-0x30, 0, sizeof(myPins)/2 - 1)],HIGH);
  
  analogWrite(PIN_PB4, (velocity*2));
  
  if(Inst == 0) previousMillis = currentMillis;
}

void MyHandleNoteOff(byte channel, byte pitch, byte velocity) {
  Serial.print("NoteOff ");
  Serial.print("Channel:  ");
  Serial.print(channel);
  Serial.print(", Pitch:  ");
  Serial.print(pitch,HEX);
  Serial.print(", Velocity:  ");
  Serial.println(velocity,HEX);

  counter--;
  
  digitalWrite(myPins[constrain(pitch-0x30, 0, sizeof(myPins)/2 - 1)],LOW);
  if(counter == 0) analogWrite(PIN_PB4, 0);
}

void setup() {
  MyMIDI.begin(MIDIChannel);
  MyMIDI.setHandleNoteOn(MyHandleNoteOn);
  MyMIDI.setHandleNoteOff(MyHandleNoteOff);

  r.begin();

  Serial.begin(115200);
  
  if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }
  display.clearDisplay();
  display.display();

  pinMode(PIN_PE3, OUTPUT);
  digitalWrite(PIN_PE3, HIGH);

  analogWrite(PIN_PB4, 0);
  
  for (int i = 0; i < sizeof(myPins)/2; i = i + 1) {
    pinMode(myPins[i], OUTPUT);
  }

  displayPrint("MIDI", 'C', 0, 2, 'W');
  displayPrint("SEQUENCER", 'C', 1, 2, 'W');
  displayPrint("by Martin Musinka", 'C', 6, 1, 'W');
  display.display();

  delay(5000);

  display.clearDisplay(); 
  displayPrint("LEDs", 'L', 0, 2, 'W');
  displayPrint("On", 'C', 2, 2, 'W');
  display.display();
}

void loop() {
  MyMIDI.read();
  StateMachine();
}
