const WebSocket = require('ws')
const osc = require('osc')
const midi = require('midi')

const ip = process.argv[2]

const DEBUG = {
  midi: true,
  osc: false
}

let mo = null
let mi = null

// Midi init
mo = new midi.Output()
mi = new midi.Input()
mo.openVirtualPort("kegel")
mi.openVirtualPort("ww-midi-in")

const oscWS = new osc.WebSocketPort({
  url: `ws://${ip}:6676`,
  metadata: false
})

oscWS.on('ready', () => {
  console.log(`Povezan sem na ${ip}`)

  /*
  setInterval(() => {
    console.log('ping')
    oscWS.send({ address: '/ping', args: [true]})
  }, 500)
  */
})

const zaznava = [2, 2, 2, 2, 2, 2]
const utisaj_vse = 0.2
let utisaj_c = [0, 0, 0, 0, 0, 0]
let cakaj = [false, false, false, false, false, false]

const cakajInterval = 1 / 5
const razponTona = [0.1, 0.5]
//const razponTona = [0.001, 0.002]

let rotVisina = 0

// Helper funkcije
const norm = (val, min, max) => {
  const d = 0 - min;
  const r = max - min
  return Math.min(1, (Math.max(min, val) + d) / r);
}
const normSin = val => {
  return norm(Math.sin(val), -1, 1);
}

const normMidi = (val, min, max) => Math.round(norm(val, min, max) * 127)
const abs = Math.abs;

oscWS.on('message', ({ address, args }) => {
  DEBUG.osc && console.log('MSG OSC', address, args.map(x => x.toFixed(4)))

  // Wavey Wind sporočila
  const re = /\/ww\/0\/ww\/(\d+)\/([a-zA-Z]+)/
  const m = address.match(re)

  if (m) {
    const index = parseInt(m[1])
    const addr = m[2]

    if (addr == 'euler') {
      //const eVisina = Math.sin(args[0] + args[1])
      const eVisina = Math.sin(args[2])
      rotVisina = 24 + Math.round(((eVisina / 2) + 0.5) * 24)
      //console.log("rotVisina", rotVisina)
    }

    if (addr == 'accel') {
      const acX = args[0]
      const acY = args[1]
      const acZ = args[2]

      // Y os je kegel po dolgem - ignoriramo
      const vsota = Math.abs(acX) + Math.abs(acZ)

      if (vsota > zaznava[index] && !cakaj[index]) {

        cakaj[index] = true

        // Pavza
        setTimeout(() => {
          //console.log("nehaj cakat")
          cakaj[index] = false
        }, cakajInterval * 1000)

        const midiKanal = 144 + index

        // Od 24 do 48
        //const accval = Math.sin((vsota - zaznava[index]) / 3)
        //const accval = (vsota - zaznava[index]) / 3
        const accval = vsota - zaznava[index]

        //console.log(acX, accval)
        // Acc visina
        const visina = (midiKanal == 144)
              ? 24 + Math.round(norm(accval, 0, 7) * 36)
              : 36 + Math.round(norm(accval, 0, 7) * 36)

        let vel = (midiKanal == 144)
            ? (visina  - 24) * (127 / 36)
            : (visina - 36) * (127 / 36)

        vel = Math.min(Math.round(vel), 127)

        console.log('posiljam midi', midiKanal, [midiKanal, visina, vel])
        mo.send([midiKanal, visina, vel])
        oscWS.send({
          address: '/midi',
          args: [midiKanal, visina, vel]
        })

        // Ugasni cez en cas
        let izklop = razponTona[0] + Math.random() * (razponTona[1] - razponTona[0])
        console.log('izklopim', midiKanal, visina, 'cez', izklop)
        setTimeout(() => {
          mo.send([midiKanal, visina, 0]);
          oscWS.send({
            address: '/midi',
            args: [midiKanal, visina, 0]
          })
          console.log('izklopi', midiKanal, visina)
        }, izklop * 1000) 
      }

      // Ce izrazito ni gibanja, utisaj vse!
      if (!utisaj_c[index]) {
        utisaj_c[index] = 0
      }
      if (vsota < utisaj_vse) {
        if (utisaj_c[index] > 10) {
          const midiKanal = 144 + index
          const visina = (midiKanal == 0)
                ? 24
                : 48
          const visina_razpon = (midiKanal == 0)
                ? 36
                : 72
          console.log("UTISAJ", index)
          for (let i = visina; i < visina + visina_razpon; i++) {
            mo.send([midiKanal, i, 0])
          }
          utisaj_c[index] = 0
        } else {
          // console.log('.')
          utisaj_c[index] += 1
        }
      } else {
        utisaj_c[index] = 0
      }
    }

    if (addr == 'midi') {
      const args = message
      console.log('OSC midi in', args) 

      mo.send(message)
      oscWS.send({
        address: '/midi-in',
        args: message
      })

      // Ugasni cez en cas
      let izklop = razponTona[0] + Math.random() * (razponTona[1] - razponTona[0])
      setTimeout(() => {
        mo.send([150, message[1], 0])
        console.log('izklopi', 150, message[1])
      }, izklop * 1000)
    }

  } else {
    console.log(address)
  }
})

mi.on('message', (deltaTime, message) => {
  console.log(`midi in: ${message} d: ${deltaTime}`);
  const args = message

  mo.send(message)
  oscWS.send({
    address: '/midi-in',
    args: message
  })

  // Ugasni cez en cas
  let izklop = razponTona[0] + Math.random() * (razponTona[1] - razponTona[0])
  setTimeout(() => {
    mo.send([150, message[1], 0])
    //console.log('izklopi zogice', 150, message[1])
  }, izklop * 1000) 
})
 

oscWS.open()
