import WebSocket from 'ws';
import { logger } from '../logger';
function broadcast(wss, message) {
  wss.clients.forEach(ws => {
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify(message));
    }
  });
}
export default function creeveyApi(runner) {
  return {
    subscribe(wss) {
      runner.on('update', payload => broadcast(wss, {
        type: 'update',
        payload
      }));
    },
    handleMessage(ws, message) {
      if (typeof message != 'string') {
        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;
          }
      }
    }
  };
}