export function emitEvent(name, data = null) {
  if (data !== null && data !== undefined) {
    window.dispatchEvent(new CustomEvent(`ncp:${name}`, { detail: data }));
  } else {
    window.dispatchEvent(new Event(`ncp:${name}`));
  }
}

export function listenTo(name, callback) {
  if (!Array.isArray(name)) {
    name = [name];
  }

  for (const n of name) {
    window.addEventListener(`ncp:${n}`, callback);
  }
}

export function awaitEvent(name) {
  return new Promise(resolve => {
    const callback = (e) => {
      resolve(e);
      window.removeEventListener(`ncp:${name}`, callback);
    };
    window.addEventListener(`ncp:${name}`, callback);
  });
}
