var path = require('path');
var fs = require('fs');

var schemaContents = fs.readFileSync(path.join(__dirname, 'oce.proto'));
var proto = require('protocol-buffers')(schemaContents);
var obj = require('protobuf-schema').parse(schemaContents);

var argumentHintParser = require('./arguments');
var getResponseArray = require('./response');

var response = proto.NetOCE_Response;
var request = proto.NetOCE_Request;

// extract the message type enum
var ENUM = obj.messages.filter(function(msg) {
  return msg.name === 'NetOCE_Value';
})[0].enums[0].values;

module.exports = createClient;
createClient.request =  proto.NetOCE_Request;
createClient.response =  proto.NetOCE_Response;

function createClient(stream, cb) {
  stream.once('data', function(first) {
    var r = response.decode(first);

    var queue = {};
    stream.done = function() {
      return !Object.keys(queue).length;
    };

    stream.on('data', function(data) {
      var obj = response.decode(data);
      var fn = queue[obj.seq];

      delete queue[obj.seq];
      getResponseArray(obj, fn);
    });

    var methods = {};
    var seq = 1;
    r.value.forEach(function(op) {
      var id = op.operation.id;

      var genfn = methods[op.operation.name] = function(a, fn) {
        var args;

        if (Array.isArray(a)) {
          args = a;
        } else {
          args = [];
          Array.prototype.push.apply(args, arguments);
          fn = args.pop();
        }

        var obj = {
          method : id,
          seq: seq++,
          argument: argumentHintParser(op.operation.arguments, args, ENUM)
        };

        queue[obj.seq] = fn;

        stream.write(request.encode(obj));
      };

      var parts = op.operation.arguments.replace(/ /g, '').split(',');
      var infinite = parts[parts.length-1].indexOf('..') > -1;
      genfn.argc = (infinite) ? Infinity : parts.length;
    });

    cb(null, methods);
  });

  stream.write(request.encode({ method: 0, seq: 0 }));

  return stream;
}

@@ -87,18 +87,8 @@
 ync(
-path.join(
 __di
@@ -92,19 +92,21 @@
 _dirname
-,
+ +
  '
+/
 oce.prot
@@ -107,17 +107,35 @@
 e.proto'
-)
+, 'utf8').toString(
 );%0Avar p
@@ -686,16 +686,160 @@
 ponse;%0A%0A
+function decode(buffer) %7B%0A  if (buffer.byteLength) %7B%0A    buffer = new Buffer(new Uint8Array(buffer));%0A  %7D%0A%0A  return response.decode(buffer);%0A%7D%0A%0A
 function
@@ -866,16 +866,16 @@
 , cb) %7B%0A
-
   stream
@@ -918,25 +918,16 @@
 var r = 
-response.
 decode(f
@@ -933,17 +933,16 @@
 first);%0A
-%0A
     var 
@@ -1068,24 +1068,24 @@
 ion(data) %7B%0A
+
       var ob
@@ -1088,25 +1088,16 @@
 r obj = 
-response.
 decode(d

work around brfs bug and typedarray bug