{"size": 1805, "ext": "js", "max_stars_repo_path": "src/JsonRpc.js", "max_stars_repo_name": "3x3ption/KodiApi.js", "max_stars_repo_stars_event_min_datetime": "2016-04-22T11:46:42.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-02T09:39:45.000Z", "max_issues_repo_path": "src/JsonRpc.js", "max_issues_repo_name": "3x3ption/KodiApi.js", "max_issues_repo_issues_event_min_datetime": "2016-04-19T09:17:43.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-22T11:45:14.000Z", "max_forks_repo_path": "src/JsonRpc.js", "max_forks_repo_name": "breadlesscode/KodiApi.js", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 4, "max_issues_count": 1, "max_forks_count": null, "avg_line_length": 25.7857142857, "max_line_length": 84, "alphanum_fraction": 0.5911357341}
class JsonRpc {
  constructor(url) {
    this.url = url;
    this.socket = new WebSocket(url);
    this.lastId = 0;
    this.methodCalls = [];
    this.onNotification = function() {};

    this.socket.onmessage = function(event) {
      let data = JSON.parse(event.data);

      if(data.id === undefined)
        return this.onNotification(data);

      if(data.result != undefined) {
        this.methodCalls[data.id].resolve(data);
      }
      else
        this.methodCalls[data.id].reject(data);

      delete this.methodCalls[data.id];
    }.bind(this)
  }
  cmd(method, ...parameters) {
    if(parameters.length === 1)
      parameters = typeof parameters[0] === 'object' ? parameters[0] : parameters;

    let requestObj = this.getRequestObject(method, parameters);

    return new Promise(function(resolve, reject) {
      this.waitForConnection(function () {
        this.methodCalls[requestObj.id] = {
          resolve: resolve,
          reject: reject,
          request: requestObj
        };
        // send request
        this.socket.send(JSON.stringify(requestObj));
      }.bind(this), 1000);
    }.bind(this));
  }
  batch(cmds) {
    // TODO
  }
  getRequestObject(method, parameters) {
    return {
      jsonrpc: "2.0",
      method: method,
      params: parameters,
      id: this.nextId
    }
  }
  get nextId() {
    this.lastId = String(new Date().getTime()) + Math.floor((Math.random() * 100));;
    return this.lastId;
  }
  waitForConnection(callback, interval) {
    if (this.socket.readyState === 1) {
      return callback();
    } else {
        var that = this;
        // optional: implement backoff for interval here
        setTimeout(function () {
            that.waitForConnection(callback, interval);
        }, interval);
    }
  }
}

module.exports = JsonRpc;