import { Errors } from './errors';
import { NAP, NAPMessage } from './external-interfaces';
import { Marshalling } from './marshalling';
import { createMessageStreams } from './message-streams';
import { createMessageSubscription } from './message-subscribers';

/**
 *  Internal interface describing the expected bridge provided
 *  by the host system.
 *  @internal
 */
interface NAPHostBridge {
  setCallback: (handler: { handle: (message: string) => void }) => void;
  send: (message: string) => void;
}
/**
 *  Declare the interface on typescript globalThis
 *  @internal
 */
declare global {
  interface Window {
    /* eslint-disable  @typescript-eslint/no-explicit-any */
    NAP?: any;
  }
}

const innerCreateNAP = (): NAP => {
  /**
   * Creates an instance of the MessageStreams
   */
  const {
    fromHost$,
    toHost$,
    errors$,
    postError,
    setToHostCallback,
    postMessageFromHost,
  } = createMessageStreams();

  /**
   * Creates an instance of the MessageStreams
   */
  const {
    notifySubscribers,
    subscribe,
    unsubscribe,
  } = createMessageSubscription();

  /**
   * Check and fetch the Javascript object injected by the host
   */
  let temporaryHostBridge;
  let hostBridge: NAPHostBridge | undefined = undefined;
  try {
    temporaryHostBridge =
      window !== undefined ? ((window as Window)['NAP'] as NAPHostBridge) : undefined;
  } finally {
    hostBridge = temporaryHostBridge;
    if (!hostBridge) {
      postError(Errors.NO_HOSTBRIDGE_100);
    }
  }

  /**
  * Wraps the hostBridge.send(string) in a function
  * sendMessage(NAPMessage) that takes a NAPMessage
  * object and JSON.stringifies it before it is
  * send through the hostBridge
  */
  let temporarySendMessage;
  if (hostBridge && typeof hostBridge.send === 'function') {
    temporarySendMessage = (message: NAPMessage): void => {
      const marshalledMessage = Marshalling.fromMessage(message, postError);
      if (marshalledMessage) {
        hostBridge?.send(marshalledMessage);
      }
    };
  } else {
    temporarySendMessage = (): void => {
      postError(Errors.MALFORMED_HOSTBRIDGE_SEND_EVEN_THOUGH_MISSING_107);
    };
    postError(Errors.MALFORMED_HOSTBRIDGE_SEND_106);
  }

  const sendMessage = temporarySendMessage;

  /**
   * Bind the toHost channel to the send handle
   * All events posted to the the toHost$(aka innerToHost$
   * - see below) will be arguments in successive calls
   * to sendMessage()
   */
  setToHostCallback(sendMessage);

  /**
   * Bind the fromHost stream and the message subcribers to
   * the callback handle of the hostBridge.
   * All calls from the host to registered callback will
   * lead to events posted on the innerFromHost$ subject
   * and all message subscribers being notified.
   */
  if (hostBridge && typeof hostBridge.setCallback === 'function') {
    hostBridge.setCallback({
      handle: (message: string) => {
        const napMessage = Marshalling.toMessage(message, postError);
        if (napMessage) {
          notifySubscribers(napMessage);
          postMessageFromHost(napMessage);
        }
      },
    });
  } else {
    postError(Errors.MALFORMED_HOSTBRIDGE_SET_CALLBACK_105);
  }

  /**
   * Sets up the external interface for the NAP SDK
   */
  return {
    fromHost$,
    toHost$,
    errors$,
    send: sendMessage,
    subscribe,
    unsubscribe,
  } as NAP;
};

/*
 * Re-export of external interfaces
 */
export { FHIR, FHIRValueGetter, FHIRValueSetter } from './event-catalogue';
export { EventCatalogue as NAPEventCatalogue, EventCatalogues } from './event-catalogue/event-catalogue';
export { NAPEventType } from './event-catalogue/event-type';
export {
  NAP,
  NAPError,
  NAPEvent,
  NAPHostSubscriber,
  NAPMessage
} from './external-interfaces';
export { filterEvent, filterEvents, NAPPatientInfo } from './utilities';
/**
 * Set window.status property to indicate that embeded mode is supported
 */
window['status'] = 'NAP-EMBEDDED-MODE';

/**
 *  Final export of the initialization function
 */
export const createNAP = innerCreateNAP;
