import type { View } from "../pages/registry";
import { SDK_CHANNEL, SDK_VERSION, type PageCommand, type PageMessage } from "./protocol";

export type {
  PageLifecycle,
  PageLifecycleEvent,
  PageLifecycleEventType,
  PageLifecycleListener,
  PageLifecycleSource,
  PageLifecycleState,
} from "./lifecycle";

export function notifyReady(view: View): void {
  send({
    channel: SDK_CHANNEL,
    version: SDK_VERSION,
    source: "page",
    type: "ready",
    view,
  });
}

export function sendCommand(view: View, command: PageCommand): void {
  send({
    channel: SDK_CHANNEL,
    version: SDK_VERSION,
    source: "page",
    type: "command",
    view,
    command,
  });
}

function send(message: PageMessage): void {
  window.parent.postMessage(message, window.location.origin);
}
