"use strict"

const ppb = require("pull-protocol-buffers").pull
const pull = require("pull-stream")
const empty = require("protocol-buffers")("message PeerCmd {required bool empty = 1;}").PeerCmd.encode({
  empty: true
})

module.exports = function LProtocol(opt, lp2p) {

  const self = this
  const swarm = lp2p.libp2p
  const protos = self.protos = {}

  if (!opt) opt = {}

  self.handle = (name, proto) => {
    protos[name] = proto
    swarm.handle("/zn/" + name + "/2.0.0", (protocol, conn) => {
      pull(
        conn,
        ppb.decode(proto.in.proto.msg),
        pull.take(1),
        pull.asyncMap((data, cb) => {
          console.log("prc", data,cb)
          proto.peerRequest.handleRequest(cb, data, proto.handler)
        }),
        ppb.encode(proto.out.proto.msg),
        conn
      )
    })
  }

  lp2p.cmd = (peer, cmd, data, cb) => {
    if (!protos[cmd]) return cb(new Error("CMD Unsupported"))
    const proto = protos[cmd]
    lp2p.dial(peer, "/zn/" + cmd + "/2.0.0", (err, conn) => {
      if (err) return cb(err)
      proto.peerRequest.sendRequest((data, cb) => {
        pull(
          pull.values([data]),
          ppb.encode(proto.in.proto.msg),
          pull.collect((err, data) => {
            if (err) return cb(err)
            if (!data.length) data = [empty]
            pull(
              pull.values(data),
              conn,
              ppb.decode(proto.out.def),
              pull.collect((err, data) => {
                if (err) return cb(err)
                else {
                  if (data.length != 1) cb(new Error("Decoding failed! data.len != 1"))
                  return cb(null, data[0])
                }
              })
            )
          })
        )
      }, data, cb)
    })
  }

}

@@ -214,16 +214,99 @@
  true%0A%7D)
+%0Aconst once = require(%22once%22)%0Aconst plog = () =%3E pull.map(d =%3E console.log(d) %7C%7C d)
 %0A%0Amodule
@@ -595,32 +595,39 @@
 ll(%0A        conn
+.source
 ,%0A        ppb.de
@@ -713,48 +713,8 @@
 ) =%3E
- %7B%0A          console.log(%22prc%22, data,cb)
 %0A   
@@ -780,18 +780,8 @@
 ler)
-%0A        %7D
 ),%0A 
@@ -832,16 +832,21 @@
     conn
+.sink
 %0A      )
@@ -885,24 +885,25 @@
  cmd, data, 
+_
 cb) =%3E %7B%0A   
@@ -895,24 +895,49 @@
 , _cb) =%3E %7B%0A
+    const cb = once(_cb)%0A
     if (!pro
@@ -1351,16 +1351,35 @@
 a.length
+ %7C%7C !data%5B0%5D.length
 ) data =
@@ -1458,16 +1458,38 @@
   conn,%0A
+              plog(),%0A
         
@@ -1519,11 +1519,17 @@
 out.
-def
+proto.msg
 ),%0A 

Fix protobuf proto