const midi = require('midi')
const readline = require('readline');

let mo = new midi.Output()
let mi = new midi.Input()

mo.openVirtualPort("debug-out")
mi.openVirtualPort("debug-in")

mi.on('message', (deltaTime, message) => {
  // The message is an array of numbers corresponding to the MIDI bytes:
  //   [status, data1, data2]
  // https://www.cs.cf.ac.uk/Dave/Multimedia/node158.html has some helpful
  // information interpreting the messages.
  console.log(`midi in: ${message} d: ${deltaTime}`)
  mo.send(message)
})



// Formiraj CC midi sporočilo
// 176+ = CC
const cc = (a, b) => ([176, a, b])

const quantize = [
  cc(40, 22),
  cc(40, 0),
  cc(40, 23)
]

const pause = [
  cc(20, 0),
  cc(20, 23)
]

const play = [
  cc(20, 0),
  cc(20, 22)
]

const posnemiTakt = [
  cc(101, 3),
  cc(102, 3),
  cc(103, 3),
  cc(104, 3),
  cc(105, 3),
  cc(106, 3),
  cc(107, 3),
  cc(108, 3),
  cc(30, 9),
  cc(101, 60),
  cc(102, 9),
  cc(103, 118),
  cc(104, 118),
  cc(105, 0),
  cc(106, 0),
  cc(107, 0),
  cc(108, 0),
  cc(30, 0),
  cc(30, 11)
]

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})

const posljiMidi = (ukazi) => {
  ukazi.forEach(midi => {
    console.log('posiljam midi', midi)
    mo.send(midi)
  })
}

rl.setPrompt('Vpiši ukaz > ')
rl.prompt()

rl.on('line', line => {
  console.log(line)
  switch (line) {
  case 'q':
    posljiMidi(quantize)
    break;
  case 'p':
    posljiMidi(play)
    break;
  case 's':
    posljiMidi(pause)
    break;
  }
  rl.prompt()
})
