import { ipcMain } from "electron";
import produce from "immer";
import { MessageId } from "./types";
import Window from "./Window";
import { copyObject } from "../utils";

export type StoreChangeArgs = {
  windowId: string;
  store: object;
};

let store: object | undefined;

export function init(): void {
  ipcMain.on(MessageId.StoreToMain, (event, args: StoreChangeArgs) => {
    storeToMain(args);
    event.reply(MessageId.StoreToMainReply, args);
  });
}

function storeToMain(args: StoreChangeArgs): void {
  if (!store) {
    store = {};
  }
  store = produce(store, draftStore => {
    copyObject(args.store, draftStore);
  });
  for (const window of Window.windows) {
    if (window.windowId !== args.windowId) {
      storeToView(window);
    }
  }
}

export function storeToView(window: Window): void {
  if (store) {
    const args: StoreChangeArgs = { windowId: window.windowId, store };
    window.window?.webContents.send(MessageId.StoreToView, args);
  }
}
