#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <alsa/asoundlib.h>

extern struct timespec timespec_diff(struct timespec start, struct timespec end);
extern double timespec_millis(struct timespec time);

snd_seq_t *open_seq();
void midi_action(snd_seq_t *seq_handle);
int keep_walking;

static void sigint_handler(int i){
  keep_walking = 0;
}



int main(int argc, char *argv[]) {

   int note_on_time = 1000000; // 1 segundo
   int note_off_time = 1000000; // 1 segundo (em microsegundos)

   signal(SIGINT, &sigint_handler);
   signal(SIGTERM, &sigint_handler);
   keep_walking = 1;

    // Crio o dispositivo MIDI
   snd_seq_t *seq_handle;
   int portid;
   if (snd_seq_open(&seq_handle, "hw", SND_SEQ_OPEN_DUPLEX, 0) < 0) {
      fprintf(stderr, "Error opening ALSA sequencer.\n");
      exit(1);
   }
   snd_seq_set_client_name(seq_handle, "Teclado");
   if ((portid = snd_seq_create_simple_port(seq_handle, "keyb",
            SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ,
            SND_SEQ_PORT_TYPE_APPLICATION)) < 0) {
      fprintf(stderr, "Error creating sequencer port.\n");
      exit(1);
   }

    snd_seq_event_t ev;
    snd_seq_ev_clear(&ev);
    snd_seq_ev_set_source(&ev, 0);
    snd_seq_ev_set_subs(&ev);
    snd_seq_ev_set_direct(&ev);

  while (keep_walking) {

    int key = getchar();
    printf("Pressionou o %d\n", key);
    switch(key){
        case 'a': 
            snd_seq_ev_set_noteon(&ev, 0, 60, 127);
            snd_seq_event_output(seq_handle, &ev);
            snd_seq_drain_output(seq_handle);
            usleep(note_on_time / 3);

            snd_seq_ev_set_noteoff(&ev, 0, 60, 0);
            snd_seq_event_output(seq_handle, &ev);
            snd_seq_drain_output(seq_handle);
            break;
        case 's':
            snd_seq_ev_set_noteon(&ev, 0, 62, 127);
            snd_seq_event_output(seq_handle, &ev);
            snd_seq_drain_output(seq_handle);
            usleep(note_on_time / 3);

            snd_seq_ev_set_noteoff(&ev, 0, 62, 0);
            snd_seq_event_output(seq_handle, &ev);
            snd_seq_drain_output(seq_handle);

    }

  }

   snd_seq_close(seq_handle);
   return 0;
}
