var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/pisellTopology/floorPlan/useTopologyFloorPlan.ts
var useTopologyFloorPlan_exports = {};
__export(useTopologyFloorPlan_exports, {
  useTopologyFloorPlan: () => useTopologyFloorPlan
});
module.exports = __toCommonJS(useTopologyFloorPlan_exports);
var import_react = require("react");
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_topologyFloorPlanConstants = require("../topologyFloorPlanConstants");
var import_topologyFloorPlanApi = require("./topologyFloorPlanApi");
var TOPOLOGY_UNKNOWN_KIND = `${import_topologyFloorPlanConstants.TOPOLOGY_DEVICE_KIND_PREFIX}unknown`;
function buildEmptyTopologyFloorPlanPostBody(code) {
  const trimmed = code == null ? void 0 : code.trim();
  if (!trimmed) throw new Error("floor plan code is required");
  return {
    code: trimmed,
    name: { "zh-CN": "拓扑" },
    layout: {
      canvases: [{ id: "main", name: "Devices", order: 0, enabled: true }],
      canvasUi: { canCreate: false, canEdit: false },
      sceneElements: [],
      edges: []
    },
    canvas_width: 1920,
    canvas_height: 1080
  };
}
function useTopologyFloorPlan(options) {
  const { floorPlanCode, enabled = true, subscribeFloorPlanPush = false } = options;
  const [floorPlanRemoteId, setFloorPlanRemoteId] = (0, import_react.useState)(
    null
  );
  const [savedSceneElements, setSavedSceneElements] = (0, import_react.useState)(void 0);
  const [savedEdges, setSavedEdges] = (0, import_react.useState)(
    void 0
  );
  const subscriberIdRef = (0, import_react.useRef)((0, import_utils.getUniqueId)("topology-floor-plan-code"));
  const ensureByCode = (0, import_react.useCallback)(
    (code, opts) => (0, import_topologyFloorPlanApi.ensureShopFloorPlanByCode)(code, {
      ...opts,
      buildDefaultPostBody: buildEmptyTopologyFloorPlanPostBody
    }),
    []
  );
  const applyDetail = (0, import_react.useCallback)((detail) => {
    if (typeof detail.id === "number" && Number.isFinite(detail.id)) {
      setFloorPlanRemoteId(Math.trunc(detail.id));
    }
    const fromLayoutField = (0, import_materials.parseLayoutFieldToViewConfigPatch)(detail.layout);
    if (fromLayoutField) {
      setSavedSceneElements(fromLayoutField.sceneElements ?? []);
      setSavedEdges(fromLayoutField.edges ?? []);
      return;
    }
    if (Array.isArray(detail.layout)) {
      setSavedSceneElements(
        detail.layout.length > 0 ? (0, import_materials.shopLayoutToSceneElements)(
          detail.layout,
          {
            canvasId: import_topologyFloorPlanConstants.TOPOLOGY_MAIN_CANVAS_ID,
            dataSourceKey: import_topologyFloorPlanConstants.TOPOLOGY_DEVICES_DATA_SOURCE_KEY,
            rectElementKind: TOPOLOGY_UNKNOWN_KIND,
            circleElementKind: TOPOLOGY_UNKNOWN_KIND
          }
        ) : []
      );
      setSavedEdges([]);
      return;
    }
    setSavedSceneElements([]);
    setSavedEdges([]);
  }, []);
  (0, import_react.useEffect)(() => {
    if (!enabled) {
      setFloorPlanRemoteId(null);
      setSavedSceneElements(void 0);
      setSavedEdges(void 0);
    }
  }, [enabled, floorPlanCode]);
  (0, import_react.useEffect)(() => {
    if (!enabled || !floorPlanCode || subscribeFloorPlanPush) return;
    let cancelled = false;
    void ensureByCode(floorPlanCode).then((detail) => {
      if (cancelled || !detail) return;
      applyDetail(detail);
    }).catch((err) => {
      if (!cancelled) (0, import_topologyFloorPlanApi.toastFloorPlanLoadError)(err);
    });
    return () => {
      cancelled = true;
    };
  }, [enabled, floorPlanCode, subscribeFloorPlanPush, ensureByCode, applyDetail]);
  (0, import_materials.useShopFloorPlanSubscription)({
    enabled: enabled && !!floorPlanCode && subscribeFloorPlanPush,
    code: floorPlanCode,
    subscriberId: subscriberIdRef.current,
    ensureByCode,
    unsubscribeQuery: import_topologyFloorPlanApi.unsubscribeShopFloorPlanCodeQuery,
    onDetail: applyDetail,
    onLoadError: import_topologyFloorPlanApi.toastFloorPlanLoadError
  });
  const applyLocalSave = (0, import_react.useCallback)(
    (params) => {
      setSavedSceneElements(params.sceneElements);
      setSavedEdges(params.edges);
    },
    []
  );
  const setRemoteFloorPlanView = (0, import_react.useCallback)(
    (patch) => {
      if (patch == null) {
        setSavedSceneElements(void 0);
        setSavedEdges(void 0);
        return;
      }
      if (patch.sceneElements != null) {
        setSavedSceneElements(patch.sceneElements);
      }
      if (patch.edges != null) {
        setSavedEdges(patch.edges);
      }
    },
    []
  );
  return {
    floorPlanRemoteId,
    savedSceneElements,
    savedEdges,
    isLoaded: savedSceneElements !== void 0,
    applyLocalSave,
    setRemoteFloorPlanView
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useTopologyFloorPlan
});
