'use strict'

const libp2p = require('libp2p')
const TCP = require('libp2p-tcp')
const Multiplex = require('libp2p-multiplex')
const SECIO = require('libp2p-secio')
const PeerInfo = require('peer-info')
const MulticastDNS = require('libp2p-mdns')
const waterfall = require('async/waterfall')
const parallel = require('async/parallel')
const series = require('async/series')

class MyBundle extends libp2p {
  constructor (peerInfo) {
    const modules = {
      transport: [new TCP()],
      connection: {
        muxer: [Multiplex],
        crypto: [SECIO]
      },
      discovery: [
        new MulticastDNS(peerInfo, { interval: 2000 })
      ]
    }
    super(modules, peerInfo)
  }
}

function createNode (callback) {
  let node

  waterfall([
    (cb) => PeerInfo.create(cb),
    (peerInfo, cb) => {
      peerInfo.multiaddrs.add('/ip4/0.0.0.0/tcp/0')
      node = new MyBundle(peerInfo)
      node.start(cb)
    }
  ], (err) => callback(err, node))
}

parallel([
  (cb) => createNode(cb),
  (cb) => createNode(cb)
], (err, nodes) => {
  if (err) { throw err }

  const node1 = nodes[0]
  const node2 = nodes[1]

  series([
    (cb) => node1.once('peer:discovery', (peer) => node1.dial(peer, cb)),
    (cb) => setTimeout(cb, 500)
  ], (err) => {
    if (err) { throw err }

    node1.pubsub.on('news', (msg) => console.log(msg.from, msg.data.toString()))
    node1.pubsub.subscribe('news')

    setInterval(() => {
      node2.pubsub.publish('news', Buffer.from('Bird bird bird, bird is the word!'))
    }, 1000)
  })
})

@@ -1295,18 +1295,25 @@
 sub.
-on
+subscribe
 ('news',
  (ms
@@ -1308,16 +1308,22 @@
 ('news',
+%0A     
  (msg) =
@@ -1369,47 +1369,28 @@
 ng()
-))
+,
 %0A    
-node1.pubsub.subscribe('news')%0A%0A
+  () =%3E %7B%0A    
     
@@ -1405,24 +1405,28 @@
 val(() =%3E %7B%0A
+    
       node2.
@@ -1498,16 +1498,20 @@
 ord!'))%0A
+    
     %7D, 1
@@ -1515,16 +1515,31 @@
 , 1000)%0A
+      %7D)%0A    )%0A
   %7D)%0A%7D)%0A

update pubsub example