var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
import { c as create_ssr_component, e as escape, h as each, d as add_attribute, b as subscribe, g as getContext, v as validate_component } from "../../../../chunks/index-0e008fb3.js";
import { p as page } from "../../../../chunks/stores-9eb273d1.js";
import { P as Page, S as Search, g as goto } from "../../../../chunks/page-f60f0254.js";
import set from "lodash/set.js";
import get from "lodash/get.js";
const Model_header = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let { activeConfig } = $$props;
  let { model } = $$props;
  if ($$props.activeConfig === void 0 && $$bindings.activeConfig && activeConfig !== void 0)
    $$bindings.activeConfig(activeConfig);
  if ($$props.model === void 0 && $$bindings.model && model !== void 0)
    $$bindings.model(model);
  return `<div class="${"lg:flex lg:items-center lg:justify-between"}"><div class="${"flex-1 min-w-0"}"><h2 class="${"text-2xl font-bold leading-7 text-gray-900 sm:text-3xl sm:truncate"}">${escape(model.name)}</h2>
		<div class="${"mt-1 flex flex-col sm:flex-row sm:flex-wrap sm:mt-0 sm:space-x-6"}">${escape(model.description || "")}</div></div>
	<div class="${"mt-5 flex lg:mt-0 lg:ml-4"}"><span class="${"hidden sm:block"}"><button type="${"button"}" class="${"inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"}">
				<svg class="${"-ml-1 mr-2 h-5 w-5 text-gray-500"}" xmlns="${"http://www.w3.org/2000/svg"}" viewBox="${"0 0 20 20"}" fill="${"currentColor"}" aria-hidden="${"true"}"><path d="${"M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z"}"></path></svg>
				Edit Model
			</button>

			<button type="${"button"}" class="${"inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"}">
				<svg xmlns="${"http://www.w3.org/2000/svg"}" class="${"-ml-1 mr-2 h-5 w-5 text-gray-500"}" fill="${"none"}" viewBox="${"0 0 24 24"}" stroke="${"currentColor"}"><path stroke-linecap="${"round"}" stroke-linejoin="${"round"}" stroke-width="${"2"}" d="${"M12 6v6m0 0v6m0-6h6m-6 0H6"}"></path></svg>
				Create Entity
			</button>

			<button type="${"button"}" class="${"inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"}">
				<svg xmlns="${"http://www.w3.org/2000/svg"}" class="${"-ml-1 mr-2 h-5 w-5 text-gray-500"}" fill="${"none"}" viewBox="${"0 0 24 24"}" stroke="${"currentColor"}"><path stroke-linecap="${"round"}" stroke-linejoin="${"round"}" stroke-width="${"2"}" d="${"M12 6v6m0 0v6m0-6h6m-6 0H6"}"></path></svg>
				Create Entity Raw
			</button></span></div></div>`;
});
const Table = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  const COLUMN_TYPES = ["string", "boolean", "number", "date", "datetime"];
  let { activeConfig } = $$props;
  let { model } = $$props;
  let { items = [] } = $$props;
  let { columns = getColumns(model) } = $$props;
  function getColumns(model2) {
    const columns2 = Array.from((/* @__PURE__ */ new Set([
      "is_enabled",
      "name",
      "description",
      ...Object.keys(get(model2, `schema.model.properties`, {}))
    ])).values());
    const validColumns = columns2.filter((c) => COLUMN_TYPES.includes(getColumnType(model2, c)));
    const columnsWithValues = [];
    for (const c of validColumns) {
      for (const item of items) {
        if (item[c] !== void 0) {
          columnsWithValues.push(c);
          break;
        }
      }
    }
    if (columnsWithValues.length === 0) {
      columnsWithValues.push("root");
    }
    return columnsWithValues;
  }
  function getColumnType(model2, column) {
    return get(model2, `schema.model.properties.${column}.type`, "string");
  }
  function formatColumnValue(model2, column, value) {
    if (value === void 0) {
      return "";
    }
    if (get(model2, `schema.model.properties.${column}.anyOf`, null)) {
      return JSON.stringify(value);
    }
    const type = getColumnType(model2, column);
    if (type === "array") {
      if (get(model2, `schema.model.properties.${column}.items.type`) !== "object") {
        return value.join(", ");
      }
      return JSON.stringify(value);
    }
    return value;
  }
  function getColumnDescription(model2, column) {
    return get(model2, `schema.model.properties.${column}.description`, "string");
  }
  if ($$props.activeConfig === void 0 && $$bindings.activeConfig && activeConfig !== void 0)
    $$bindings.activeConfig(activeConfig);
  if ($$props.model === void 0 && $$bindings.model && model !== void 0)
    $$bindings.model(model);
  if ($$props.items === void 0 && $$bindings.items && items !== void 0)
    $$bindings.items(items);
  if ($$props.columns === void 0 && $$bindings.columns && columns !== void 0)
    $$bindings.columns(columns);
  columns = getColumns(model);
  return `<div class="${"py-2 align-middle inline-block min-w-full"}"><div class="${"shadow overflow-hidden border-b border-gray-200 sm:rounded-lg"}"><table class="${"min-w-full divide-y divide-gray-200"}"><thead class="${"bg-gray-50"}"><tr>${each(columns, (column) => {
    return `<th class="${"px-6 py-3 text-left text-xs font-medium text-gray-500 tracking-wider"}"${add_attribute("title", getColumnDescription(model, column), 0)}>${escape(column)} (${escape(getColumnType(model, column))})
						</th>`;
  })}</tr></thead>
			<tbody class="${"bg-white divide-y divide-gray-200"}">${each(items, (item, i) => {
    return `<tr>${each(columns, (column) => {
      return `<td class="${"px-6 py-3 text-left text-xs font-medium text-gray-500 tracking-wider"}"><a class="${"truncate"}"${add_attribute("href", `/datastore/${model.name}/${item[model.correlation_field]}`.toLocaleLowerCase(), 0)}>${column === "root" ? `<code>${escape(JSON.stringify(item).slice(0, 50))}</code>` : `${getColumnType(model, column) === "boolean" ? `<span class="${[
        "px-2 inline-flex text-xs leading-5 font-semibold rounded-full",
        (item[column] ? "text-green-800" : "") + " " + (item[column] ? "bg-green-100" : "") + " " + (!item[column] ? "text-red-800" : "") + " " + (!item[column] ? "bg-red-100" : "")
      ].join(" ").trim()}"><!-- HTML_TAG_START -->${formatColumnValue(model, column, item[column])}<!-- HTML_TAG_END -->
										</span>` : `${getColumnType(model, column) === "array" ? `<!-- HTML_TAG_START -->${formatColumnValue(model, column, item[column])}<!-- HTML_TAG_END -->` : `<!-- HTML_TAG_START -->${formatColumnValue(model, column, item[column])}<!-- HTML_TAG_END -->`}`}`}</a>
							</td>`;
    })}
					</tr>`;
  })}</tbody></table></div></div>`;
});
const U5Bmodelu5D = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let $datastore, $$unsubscribe_datastore;
  let $page, $$unsubscribe_page;
  let $models, $$unsubscribe_models;
  let $activeConfig, $$unsubscribe_activeConfig;
  $$unsubscribe_page = subscribe(page, (value) => $page = value);
  const models = getContext("stores").models;
  $$unsubscribe_models = subscribe(models, (value) => $models = value);
  const activeConfig = getContext("stores").activeConfig;
  $$unsubscribe_activeConfig = subscribe(activeConfig, (value) => $activeConfig = value);
  const datastore = getContext("stores").activeClient;
  $$unsubscribe_datastore = subscribe(datastore, (value) => $datastore = value);
  let model;
  let query = $page.url.searchParams.get("q") || "";
  let results = [];
  let count = 0;
  let fragments = [];
  let pattern = "";
  async function search(query2, model2) {
    if (!model2) {
      return;
    }
    const _query = {};
    fragments = query2.split(" ").map((f) => f.split("=")).filter((f) => f.length === 2);
    fragments.forEach((f) => {
      try {
        if (/\d+/.test(f[1])) {
          set(_query, f[0], f[1]);
        } else {
          set(_query, f[0], JSON.parse(f[1]));
        }
      } catch (err) {
        console.log(f[1]);
        console.error(err);
        set(_query, f[0], f[1]);
      }
    });
    pattern = query2.split(" ").map((f) => f.split("=")).filter((f) => f.filter((_f) => !!_f).length === 1).join(" ");
    const q = __spreadProps(__spreadValues({}, _query), { _must_hash: true });
    if (!!pattern) {
      q._q = {
        $or: [
          { name: { $regex: pattern, $options: "i" } },
          {
            description: { $regex: pattern, $options: "i" }
          },
          { tags: { $regex: pattern, $options: "i" } }
        ]
      };
    }
    console.log("[search] Query", q);
    const { data } = await $datastore.find(model2.name, q);
    try {
      const { data: decryptedResults } = await $datastore.decrypt(model2.name, data);
      results = decryptedResults;
    } catch (err) {
      results = data;
    }
    const res = await $datastore.count(model2.name, q);
    if (!isNaN(res)) {
      count = res;
    } else {
      count = -1;
    }
    goto(`/datastore/${model2.name}?q=${query2}`.toLowerCase(), {
      replaceState: true,
      noscroll: true,
      keepfocus: true
    });
  }
  let $$settled;
  let $$rendered;
  do {
    $$settled = true;
    model = $models && $models[$page.params.model];
    {
      search(query, model);
    }
    $$rendered = `${validate_component(Page, "Layout").$$render($$result, {}, {}, {
      main: () => {
        return `<div slot="${"main"}">${!!model ? `${validate_component(Model_header, "ModelHeader").$$render($$result, { activeConfig: $activeConfig, model }, {}, {})}

			${validate_component(Search, "Search").$$render($$result, { count, pattern, fragments, value: query }, {
          value: ($$value) => {
            query = $$value;
            $$settled = false;
          }
        }, {})}

			<div class="${"w-full overflow-x-auto "}">${results.length > 0 ? `${validate_component(Table, "Table").$$render($$result, {
          model,
          activeConfig: $activeConfig,
          items: results
        }, {}, {})}` : `<div class="${"p-20 sm:px-0 flex"}"><h3 class="${"text-lg w-full text-center font-medium leading-6 text-gray-900"}">No result found
						</h3></div>`}</div>` : ``}</div>`;
      }
    })}`;
  } while (!$$settled);
  $$unsubscribe_datastore();
  $$unsubscribe_page();
  $$unsubscribe_models();
  $$unsubscribe_activeConfig();
  return $$rendered;
});
export { U5Bmodelu5D as default };
