import { noop } from '../../types';
import { getConnectionUrl } from './helpers';
export async function initCreeveyClientApi() {
  let clientApiResolver = noop;
  const updateListeners = new Set();
  let statusRequest = null;
  let statusResolver = noop;
  const ws = new WebSocket(`ws://${getConnectionUrl()}`);
  function send(request) {
    ws.send(JSON.stringify(request));
  }
  ws.addEventListener('open', () => {
    clientApiResolver({
      start(ids) {
        send({
          type: 'start',
          payload: ids
        });
      },
      stop() {
        send({
          type: 'stop'
        });
      },
      approve(id, retry, image) {
        send({
          type: 'approve',
          payload: {
            id,
            retry,
            image
          }
        });
      },
      onUpdate(fn) {
        updateListeners.add(fn);
        return () => updateListeners.delete(fn);
      },
      get status() {
        if (statusRequest) return statusRequest;
        send({
          type: 'status'
        });
        return statusRequest = new Promise(resolve => statusResolver = resolve);
      }
    });
  });
  ws.addEventListener('message', message => {
    const data = JSON.parse(message.data);
    if (data.type == 'update') updateListeners.forEach(fn => fn(data.payload));
    if (data.type == 'status') {
      statusResolver(data.payload);
      statusResolver = noop;
      statusRequest = null;
    }
  });
  // TODO Reconnect

  return new Promise(resolve => clientApiResolver = resolve);
}