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

const ip = process.argv[2]

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

//const ws = new WebSocket(`ws://${ip}:6676`)

/*
const wsp = new osc.WebsocketClientPlugin({
  host: ip,
  port: 6676
})
*/
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.5, 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

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\/(\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)
        //console.log(acX, accval)
        // Acc visina
        const visina = (midiKanal == 0)
              ? 24 + Math.round((accval / 2.5) * 36)
              : 48 + Math.round((accval / 2.5) * 72)

        //const visina = rotVisina

        //console.log('posiljam midi', [144, visina, 127])
        /*
        oscWS.send({
          address: '/midi',
          args: [192, 0, 127]
        })
        */
        oscWS.send({
          address: '/midi',
          args: [midiKanal, visina, 127]
        })
        console.log('vklopi', midiKanal, visina)

        // Ugasni cez en cas
        let izklop = razponTona[0] + Math.random() * (razponTona[1] - razponTona[0])
	console.log('izklopim', midiKanal, visina, 'cez', izklop)
        setTimeout(() => {
          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++) {
		  oscWS.send({
		    address: '/midi',
		    args: [midiKanal, i, 0]
		  })
	  }
          utisaj_c[index] = 0
        } else {
          // console.log('.')
          utisaj_c[index] += 1
        }
      } else {
        utisaj_c[index] = 0
      }
    }
  } else {
    console.log(address)
  }

  if (address === '/midi-in') {
    console.log(args)
    oscWS.send({
      address: '/midi',
      args: [150, args[1], args[2]]
    })

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

oscWS.open()
