import React from "react";

export type AppInfo = {
  type: "appInfo";
  client: string;
  scopes: string[] | null;
};

export type Message =
  | { type: "hello" }
  | { type: "passwordSubmit"; username: string; password: string }
  | { type: "passwordSubmitResult"; success: boolean }
  | AppInfo
  | { type: "appResult"; success: boolean };

export function useDex(domain: string, handler: (msg: Message) => void) {
  const [source, setSource] = React.useState<MessageEventSource | null>(null);

  const sendToDex = (msg: Message, maybeSource?: MessageEventSource) => {
    let realSource = maybeSource ?? source;
    realSource!.postMessage(msg, {
      targetOrigin: domain
    });
  };

  React.useEffect(() => {
    window.addEventListener("message", (e) => {
      if (e.origin !== domain) return;
      const message: Message = e.data;
      setSource(e.source);

      if (message.type === "hello") {
        sendToDex({ type: "hello" }, e.source!);
      }

      handler(message);
    });
  }, []);

  return sendToDex;
}
