/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var compile_plan_exports = {};
__export(compile_plan_exports, {
  compileFlowSurfaceApplyBlueprintRequest: () => compileFlowSurfaceApplyBlueprintRequest,
  resolveApplyBlueprintPageLocator: () => resolveApplyBlueprintPageLocator
});
module.exports = __toCommonJS(compile_plan_exports);
var import_lodash = __toESM(require("lodash"));
var import_errors = require("../errors");
var import_service_utils = require("../service-utils");
var import_compile_blocks = require("./compile-blocks");
var import_compile_reaction = require("./compile-reaction");
const CREATE_MENU_ITEM_STEP_ID = "blueprintMenuItem";
const CREATE_MENU_GROUP_STEP_ID = "blueprintMenuGroup";
const CREATE_PAGE_STEP_ID = "blueprintPage";
const PAGE_CONFIGURE_STEP_ID = "blueprintPageConfigure";
function buildApplyBlueprintTabStepId(kind, tabIndex) {
  const suffix = tabIndex + 1;
  if (kind === "compose") {
    return `blueprintComposeTab__${suffix}`;
  }
  if (kind === "add") {
    return `blueprintAddTab__${suffix}`;
  }
  return `blueprintUpdateTab__${suffix}`;
}
function buildPageChrome(document) {
  var _a, _b, _c, _d;
  const firstTab = document.tabs[0];
  const pageTitle = ((_a = document.page) == null ? void 0 : _a.title) || ((_c = (_b = document.navigation) == null ? void 0 : _b.item) == null ? void 0 : _c.title) || (firstTab == null ? void 0 : firstTab.title) || "Untitled page";
  return {
    pageTitle,
    tabTitle: (firstTab == null ? void 0 : firstTab.title) || pageTitle,
    tabIcon: firstTab == null ? void 0 : firstTab.icon,
    tabDocumentTitle: firstTab == null ? void 0 : firstTab.documentTitle,
    enableTabs: ((_d = document.page) == null ? void 0 : _d.enableTabs) ?? document.tabs.length > 1
  };
}
function buildTabSelectorFromStep(stepId, path = "tabSchemaUid") {
  return {
    step: stepId,
    path
  };
}
function buildTabSelectorFromUid(uid) {
  return {
    locator: { uid }
  };
}
function compileCreatePlan(document, getCollection) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B;
  const steps = [];
  const chrome = buildPageChrome(document);
  if (import_lodash.default.isPlainObject((_a = document.navigation) == null ? void 0 : _a.group) && import_lodash.default.isUndefined(document.navigation.group.routeId)) {
    steps.push({
      id: CREATE_MENU_GROUP_STEP_ID,
      action: "createMenu",
      values: (0, import_service_utils.buildDefinedPayload)({
        title: (_c = (_b = document.navigation) == null ? void 0 : _b.group) == null ? void 0 : _c.title,
        type: "group",
        icon: (_e = (_d = document.navigation) == null ? void 0 : _d.group) == null ? void 0 : _e.icon,
        tooltip: (_g = (_f = document.navigation) == null ? void 0 : _f.group) == null ? void 0 : _g.tooltip,
        hideInMenu: (_i = (_h = document.navigation) == null ? void 0 : _h.group) == null ? void 0 : _i.hideInMenu
      })
    });
  }
  steps.push({
    id: CREATE_MENU_ITEM_STEP_ID,
    action: "createMenu",
    values: (0, import_service_utils.buildDefinedPayload)({
      title: ((_k = (_j = document.navigation) == null ? void 0 : _j.item) == null ? void 0 : _k.title) || chrome.pageTitle,
      type: "item",
      icon: ((_m = (_l = document.navigation) == null ? void 0 : _l.item) == null ? void 0 : _m.icon) || ((_n = document.page) == null ? void 0 : _n.icon) || "FileOutlined",
      tooltip: (_p = (_o = document.navigation) == null ? void 0 : _o.item) == null ? void 0 : _p.tooltip,
      hideInMenu: (_r = (_q = document.navigation) == null ? void 0 : _q.item) == null ? void 0 : _r.hideInMenu,
      parentMenuRouteId: import_lodash.default.isUndefined((_t = (_s = document.navigation) == null ? void 0 : _s.group) == null ? void 0 : _t.routeId) ? ((_v = (_u = document.navigation) == null ? void 0 : _u.group) == null ? void 0 : _v.title) ? { step: CREATE_MENU_GROUP_STEP_ID, path: "routeId" } : void 0 : (_x = (_w = document.navigation) == null ? void 0 : _w.group) == null ? void 0 : _x.routeId
    })
  });
  steps.push({
    id: CREATE_PAGE_STEP_ID,
    action: "createPage",
    values: (0, import_service_utils.buildDefinedPayload)({
      menuRouteId: { step: CREATE_MENU_ITEM_STEP_ID, path: "routeId" },
      title: chrome.pageTitle,
      icon: (_y = document.page) == null ? void 0 : _y.icon,
      documentTitle: (_z = document.page) == null ? void 0 : _z.documentTitle,
      enableHeader: (_A = document.page) == null ? void 0 : _A.enableHeader,
      enableTabs: chrome.enableTabs,
      displayTitle: (_B = document.page) == null ? void 0 : _B.displayTitle,
      tabTitle: chrome.tabTitle,
      tabIcon: chrome.tabIcon,
      tabDocumentTitle: chrome.tabDocumentTitle,
      tabSchemaName: document.tabs[0].key
    })
  });
  steps.push({
    id: buildApplyBlueprintTabStepId("compose", 0),
    action: "compose",
    selectors: {
      target: buildTabSelectorFromStep(CREATE_PAGE_STEP_ID)
    },
    values: (0, import_compile_blocks.compileTabComposeValues)(document.tabs[0], document, 0, { mode: "append", getCollection })
  });
  document.tabs.slice(1).forEach((tab, offset) => {
    const tabIndex = offset + 1;
    const addTabStepId = buildApplyBlueprintTabStepId("add", tabIndex);
    steps.push({
      id: addTabStepId,
      action: "addTab",
      selectors: {
        target: {
          step: CREATE_PAGE_STEP_ID,
          path: "pageUid"
        }
      },
      values: (0, import_service_utils.buildDefinedPayload)({
        title: tab.title || tab.key,
        icon: tab.icon,
        documentTitle: tab.documentTitle,
        tabSchemaName: tab.key
      })
    });
    steps.push({
      id: buildApplyBlueprintTabStepId("compose", tabIndex),
      action: "compose",
      selectors: {
        target: buildTabSelectorFromStep(addTabStepId)
      },
      values: (0, import_compile_blocks.compileTabComposeValues)(tab, document, tabIndex, { mode: "append", getCollection })
    });
  });
  steps.push(...(0, import_compile_reaction.compileReactionPlanSteps)(document.reaction));
  return {
    document,
    steps,
    pageLocator: {}
  };
}
function buildPageConfigureChanges(document) {
  var _a, _b, _c, _d, _e, _f;
  return (0, import_service_utils.buildDefinedPayload)({
    title: (_a = document.page) == null ? void 0 : _a.title,
    icon: (_b = document.page) == null ? void 0 : _b.icon,
    documentTitle: (_c = document.page) == null ? void 0 : _c.documentTitle,
    enableHeader: (_d = document.page) == null ? void 0 : _d.enableHeader,
    enableTabs: (_e = document.page) == null ? void 0 : _e.enableTabs,
    displayTitle: (_f = document.page) == null ? void 0 : _f.displayTitle
  });
}
function compileReplacePlan(document, targetInfo, getCollection) {
  const steps = [];
  const pageChanges = buildPageConfigureChanges(document);
  if (Object.keys(pageChanges).length) {
    steps.push({
      id: PAGE_CONFIGURE_STEP_ID,
      action: "configure",
      selectors: {
        target: {
          locator: {
            uid: targetInfo.pageUid
          }
        }
      },
      values: {
        changes: pageChanges
      }
    });
  }
  document.tabs.forEach((tab, index) => {
    const existingTab = targetInfo.tabs[index];
    if (existingTab) {
      const tabChanges = (0, import_service_utils.buildDefinedPayload)({
        title: tab.title,
        icon: tab.icon,
        documentTitle: tab.documentTitle
      });
      if (Object.keys(tabChanges).length) {
        steps.push({
          id: buildApplyBlueprintTabStepId("update", index),
          action: "updateTab",
          selectors: {
            target: buildTabSelectorFromUid(existingTab.uid)
          },
          values: tabChanges
        });
      }
      steps.push({
        id: buildApplyBlueprintTabStepId("compose", index),
        action: "compose",
        selectors: {
          target: buildTabSelectorFromUid(existingTab.uid)
        },
        values: (0, import_compile_blocks.compileTabComposeValues)(tab, document, index, { mode: "replace", getCollection })
      });
      return;
    }
    const addTabStepId = buildApplyBlueprintTabStepId("add", index);
    steps.push({
      id: addTabStepId,
      action: "addTab",
      selectors: {
        target: {
          locator: {
            uid: targetInfo.pageUid
          }
        }
      },
      values: (0, import_service_utils.buildDefinedPayload)({
        title: tab.title || tab.key,
        icon: tab.icon,
        documentTitle: tab.documentTitle,
        tabSchemaName: tab.key
      })
    });
    steps.push({
      id: buildApplyBlueprintTabStepId("compose", index),
      action: "compose",
      selectors: {
        target: buildTabSelectorFromStep(addTabStepId)
      },
      values: (0, import_compile_blocks.compileTabComposeValues)(tab, document, index, { mode: "append", getCollection })
    });
  });
  targetInfo.tabs.slice(document.tabs.length).reverse().forEach((tab, index) => {
    steps.push({
      id: `blueprintRemoveTab__${index + 1}`,
      action: "removeTab",
      selectors: {
        target: buildTabSelectorFromUid(tab.uid)
      }
    });
  });
  steps.push(...(0, import_compile_reaction.compileReactionPlanSteps)(document.reaction));
  return {
    document,
    surface: {
      locator: import_lodash.default.cloneDeep(targetInfo.locator)
    },
    steps,
    pageLocator: import_lodash.default.cloneDeep(targetInfo.locator),
    pageUid: targetInfo.pageUid
  };
}
function compileFlowSurfaceApplyBlueprintRequest(document, options = {}) {
  if (document.mode === "create") {
    return compileCreatePlan(document, options.getCollection);
  }
  if (!options.replaceTarget) {
    (0, import_errors.throwBadRequest)(`flowSurfaces applyBlueprint replace target resolution is missing`);
  }
  return compileReplacePlan(document, options.replaceTarget, options.getCollection);
}
function resolveApplyBlueprintPageLocator(program, executeResult) {
  var _a, _b, _c;
  if (program.document.mode === "replace") {
    return import_lodash.default.cloneDeep(program.pageLocator);
  }
  const resultById = Object.fromEntries(
    import_lodash.default.castArray((executeResult == null ? void 0 : executeResult.results) || []).map((item) => [String((item == null ? void 0 : item.id) || (item == null ? void 0 : item.index)), item == null ? void 0 : item.result])
  );
  const pageSchemaUid = ((_a = resultById[CREATE_PAGE_STEP_ID]) == null ? void 0 : _a.pageSchemaUid) || ((_c = (_b = executeResult == null ? void 0 : executeResult.target) == null ? void 0 : _b.locator) == null ? void 0 : _c.pageSchemaUid) || void 0;
  if (!pageSchemaUid) {
    (0, import_errors.throwBadRequest)(`flowSurfaces applyBlueprint failed to resolve created pageSchemaUid`);
  }
  return {
    pageSchemaUid: String(pageSchemaUid)
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  compileFlowSurfaceApplyBlueprintRequest,
  resolveApplyBlueprintPageLocator
});
