"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = creeveyApi;
var _ws = _interopRequireDefault(require("ws"));
var _logger = require("../logger");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function broadcast(wss, message) {
  wss.clients.forEach(ws => {
    if (ws.readyState === _ws.default.OPEN) {
      ws.send(JSON.stringify(message));
    }
  });
}
function creeveyApi(runner) {
  return {
    subscribe(wss) {
      runner.on('update', payload => broadcast(wss, {
        type: 'update',
        payload
      }));
    },
    handleMessage(ws, message) {
      if (typeof message != 'string') {
        _logger.logger.info('unhandled message', message);
        return;
      }
      const command = JSON.parse(message);
      switch (command.type) {
        case 'status':
          {
            ws.send(JSON.stringify({
              type: 'status',
              payload: runner.status
            }));
            return;
          }
        case 'start':
          {
            runner.start(command.payload);
            return;
          }
        case 'stop':
          {
            runner.stop();
            return;
          }
        case 'approve':
          {
            void runner.approve(command.payload);
            return;
          }
      }
    }
  };
}