const osc = require("osc");
const udp = new osc.UDPPort({
  localAddress: '0.0.0.0', //<-- NOTE: '127.0.0.1' doesn't work!! for comm. between different machines
  localPort: 57001, remoteAddress: '0.0.0.0', remotePort: 57000, metadata: true
});

//firstly establish/prepare osc conn.
Promise.all([
  new Promise((resolve, reject) => udp.on("ready", () => resolve('resolve: udp ready.'))),
]).then(results => {
  console.log(results[0]);

  const io = require('socket.io-client');
  const socket = io('https://walkingtowardstheflow.xyz');

  socket.on('connect', () => {
    console.log("[osc-receiver] i'm connected.");
    socket.emit("room", 1, (res) => console.log(res));
  });
  socket.on('disconnect', () => console.log("[osc-receiver] i'm disconnected."));

  //from browser
  socket.on('post', p => {
    console.log('post', p);
  });

  //from puredata
  udp.on("message", function (m) {
      // console.log("osc(pd)", m);

      //
      if (m.address == '/flow') {
        socket.emit('flow', m.args[0].value);
      }

      //
      else if (m.address == '/info') {
        socket.emit('info', (fields) => {
          console.log(fields.length);
          //
          var flags = [];
          for (let k = 0; k < fields.length; k++) {
            if (fields[k].group == "flag") flags.push({type:'f', value:k});
          }
          udp.send({
            address: '/info/flags',
            args: flags
          })
          //
          var bodies = [];
          for (let k = 0; k < fields.length; k++) {
            if (fields[k].group == "body") bodies.push({type:'f', value:k});
          }
          udp.send({
            address: '/info/bodies',
            args: bodies
          })
          //
          var objects = [];
          for (let k = 0; k < fields.length; k++) {
            if (fields[k].group == "object") objects.push({type:'f', value:k});
          }
          udp.send({
            address: '/info/objects',
            args: objects
          })
          //
          var ones = [];
          for (let k = 0; k < fields.length; k++) {
            if (fields[k].group == "any") ones.push({type:'f', value:k});
          }
          udp.send({
            address: '/info/ones',
            args: ones
          })
          //
          udp.send({
            address: '/info/entries',
            args:[
              {type: 'f', value: fields.length},
              {type: 'f', value: flags.length},
              {type: 'f', value: bodies.length},
              {type: 'f', value: objects.length},
              {type: 'f', value: ones.length},
            ]
          });
        });
      }
  });

});

//osc.js - start service
udp.open();
udp.on("ready", () => console.log(
  "[udp] ready (udp) : \n" +
  "\tlistening on --> " + udp.options.localAddress + ":" + udp.options.localPort + "\n" +
  "\tspeaking to -> " + udp.options.remoteAddress + ":" + udp.options.remotePort + "\n"
));
