export const PLAYER_ACTIONS = Object.freeze({
  FORCE_PLAY: 'forcePlay',
  RESTART: 'restart',
  TOGGLE_PAUSE: 'togglePause',
  UNLOCK_AUDIO: 'unlockAudio',
});

export const EDITOR_EVENTS = Object.freeze({
  AUDIO_PLAYING: 'audioPlaying',
  LOADING_COMPLETE: 'loadingComplete',
  LOADING_ERROR: 'loadingError',
  LOADING_PROGRESS: 'loadingProgress',
  PLAY_STATE_CHANGED: 'playStateChanged',
});

const playerActions = new Set(Object.values(PLAYER_ACTIONS));
const editorEvents = new Set(Object.values(EDITOR_EVENTS));

function isTrustedMessage(event, expectedSource, expectedOrigin) {
  return Boolean(
    event
    && event.source === expectedSource
    && event.origin === expectedOrigin
    && event.data
    && typeof event.data === 'object'
  );
}

export function isPlayerControlMessage(event, expectedSource, expectedOrigin) {
  return isTrustedMessage(event, expectedSource, expectedOrigin)
    && playerActions.has(event.data.action);
}

export function isEditorEventMessage(event, expectedSource, expectedOrigin) {
  return isTrustedMessage(event, expectedSource, expectedOrigin)
    && editorEvents.has(event.data.type);
}
