import { safeLocalStorage, REFERENCE_LS_KEYS } from "@scalar/helpers/object/local-storage";
import { generateClientMutators } from "@scalar/workspace-store/client";
import { onCustomEvent } from "@scalar/workspace-store/events";
const useWorkspaceStoreEvents = (store, root) => {
  const mutators = generateClientMutators(store);
  onCustomEvent(root, "scalar-update-dark-mode", (event) => {
    store.update("x-scalar-color-mode", event.detail.value ? "dark" : "light");
  });
  onCustomEvent(root, "scalar-update-active-document", (event) => {
    store.update("x-scalar-active-document", event.detail.value);
  });
  onCustomEvent(root, "scalar-update-selected-client", (event) => {
    store.update("x-scalar-default-client", event.detail);
    safeLocalStorage().setItem(REFERENCE_LS_KEYS.SELECTED_CLIENT, event.detail);
  });
  onCustomEvent(root, "scalar-replace-servers", (event) => {
    const activeDocument = store.workspace.activeDocument;
    if (!activeDocument) {
      return;
    }
    activeDocument.servers = event.detail.servers;
    activeDocument["x-scalar-active-server"] = event.detail.servers.at(-1)?.url;
  });
  onCustomEvent(root, "scalar-update-selected-server", (event) => {
    const activeDocument = store.workspace.activeDocument;
    if (activeDocument) {
      activeDocument["x-scalar-active-server"] = event.detail.value;
    }
  });
  onCustomEvent(root, "store-update-selected-server-properties", (event) => {
    const activeDocument = store.workspace.activeDocument;
    if (!activeDocument) {
      return;
    }
    const activeServer = activeDocument["servers"]?.find((it) => it.url === activeDocument["x-scalar-active-server"]);
    if (!activeServer) {
      return;
    }
    activeServer[event.detail.key] = event.detail.value;
  });
  onCustomEvent(root, "scalar-update-selected-server-variables", (event) => {
    const activeDocument = store.workspace.activeDocument;
    if (!activeDocument) {
      return;
    }
    const activeServer = activeDocument["servers"]?.find((it) => it.url === activeDocument["x-scalar-active-server"]);
    if (!activeServer) {
      return;
    }
    const variable = activeServer.variables?.[event.detail.key];
    if (variable) {
      variable.default = event.detail.value;
    }
  });
  onCustomEvent(root, "scalar-add-server", (event) => {
    mutators.active().serverMutators.addServer(event.detail.server);
    const activeDocument = store.workspace.activeDocument;
    if (activeDocument) {
      activeDocument["x-scalar-active-server"] = event.detail.server.url;
    }
  });
  onCustomEvent(root, "scalar-delete-server", (event) => {
    mutators.active().serverMutators.deleteServer(event.detail.url);
  });
};
export {
  useWorkspaceStoreEvents
};
