/* eslint-disable no-undef, no-unused-vars, no-redeclare */

// package: nanoapp.std.shell
// file: shell.proto

var shell_pb = require("./shell_pb");
var grpc = require("@improbable-eng/grpc-web").grpc;

var Command = (function () {
  function Command() {}
  Command.serviceName = "nanoapp.std.shell.Command";
  return Command;
}());

Command.Exec = {
  methodName: "Exec",
  service: Command,
  requestStream: false,
  responseStream: true,
  requestType: shell_pb.CommandReq,
  responseType: shell_pb.CommandRes
};

exports.Command = Command;

function CommandClient(serviceHost, options) {
  this.serviceHost = serviceHost;
  this.options = options || {};
}

CommandClient.prototype.exec = function exec(requestMessage, metadata) {
  var listeners = {
    data: [],
    end: [],
    status: []
  };
  var client = grpc.invoke(Command.Exec, {
    request: requestMessage,
    host: this.serviceHost,
    metadata: metadata,
    transport: this.options.transport,
    debug: this.options.debug,
    onMessage: function (responseMessage) {
      listeners.data.forEach(function (handler) {
        handler(responseMessage);
      });
    },
    onEnd: function (status, statusMessage, trailers) {
      listeners.status.forEach(function (handler) {
        handler({ code: status, details: statusMessage, metadata: trailers });
      });
      listeners.end.forEach(function (handler) {
        handler({ code: status, details: statusMessage, metadata: trailers });
      });
      listeners = null;
    }
  });
  return {
    on: function (type, handler) {
      listeners[type].push(handler);
      return this;
    },
    cancel: function () {
      listeners = null;
      client.close();
    }
  };
};

exports.CommandClient = CommandClient;

