import { h as l, S as x, A as W, a as B, b as K, M as $ } from "./asset.types.KXRZEtBr.js";
import "./browser.BHOCIF_A.js";
import "./lit-element.jLBm65_O.js";
import "./form.Ch1cwYzO.js";
import "./i18n.BABe9hN4.js";
import { a as V } from "./string.DUgD4c9f.js";
import "./content-builder.CcgZciZN.js";
import "./unsafe-html.Dff7-rCx.js";
function q(e) {
  return typeof e == "object" && e !== null && "URI" in e;
}
const Z = {
  artist: "Artist",
  color: "Color",
  createDate: "CreateDate",
  docSubType: "DocSubType",
  docType: "DocType",
  editDate: "EditDate",
  fileExtension: "Fileextension",
  keyword: "Keyword",
  mediaDate: "MediaDate",
  mediaNumber: "MediaNumber",
  nativeKeyword: "NativeKeyword",
  orientation: "Orientation",
  parentFolderIdentifier: "ParentFolderIdentifier",
  path: "Path",
  photographer: "Photographer",
  purpose: "Purpose",
  recordId: "RecordID",
  systemIdentifier: "SystemIdentifier",
  text: "Text",
  title: "Title"
}, X = /* @__PURE__ */ new Set(["mediaDate", "createDate", "editDate"]);
function z(e) {
  return !/[\s&+/*"\\:(),'<>~|[\]{}]/.test(e) && !/^(?:OR|AND|NOT)$/.test(e) ? e : `"${e.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
}
function R(e, t) {
  const o = (Array.isArray(t) ? t : [t]).map((s) => `${e}:${z(s)}`);
  return o.length > 1 ? `(${o.join(" OR ")})` : o[0] ?? "";
}
function Y(e, t) {
  return (Array.isArray(t) ? t : [t]).map((o) => `${e}${o.operator}${o.value}`).join(" AND ");
}
function Q(e) {
  const t = [];
  for (const r of Object.keys(e)) {
    const o = r, s = e[o];
    if (s == null)
      continue;
    if (o === "custom") {
      for (const [a, p] of Object.entries(
        s
      ))
        t.push(R(a, p));
      continue;
    }
    const u = Z[o];
    if (u) {
      if (X.has(o)) {
        t.push(
          Y(u, s)
        );
        continue;
      }
      if (o === "color") {
        t.push(`${u}:${s}`);
        continue;
      }
      t.push(R(u, s));
    }
  }
  return t.join(" AND ");
}
function _(e) {
  if ("and" in e)
    return e.and.map(_).filter(Boolean).join(" AND ");
  if ("or" in e) {
    const t = e.or.map(_).filter(Boolean);
    return t.length > 1 ? `(${t.join(" OR ")})` : t[0] ?? "";
  }
  if ("not" in e) {
    const t = _(e.not);
    return t ? `NOT (${t})` : "";
  }
  return Q(e);
}
const L = "CoreField.LargeSizePreview", O = "CoreField.DocType", J = "Document.Title", ee = "Document.CaptionLong", P = "Document.FileExtension", b = "CoreField.FileSize", G = "CoreField.Identifier", M = "CoreField.Keywords", U = "CoreField.MaxHeight", j = "CoreField.MaxWidth", D = "Document.RecordID", v = "CoreField.DocSubType", w = "CoreField.TitleWithFallback", T = "CoreField.OriginalFileName", y = "CoreField.UpdatedFileName", E = "CoreField.OriginalPreview", F = {
  DEFAULT_VIEW_SIZE: "Document.LargeSizePreview",
  FIELD_TITLE_WITH_FALLBACK: "Document.TitleWithFallback",
  ORIGINAL_VIEW_SIZE: "Document.OriginalPreview"
}, H = {
  [L]: F.DEFAULT_VIEW_SIZE,
  [w]: F.FIELD_TITLE_WITH_FALLBACK,
  [E]: F.ORIGINAL_VIEW_SIZE
}, te = Object.fromEntries(
  Object.entries(H).map(([e, t]) => [
    t,
    e
  ])
);
function re(e) {
  return H[e] ?? e;
}
function oe(e) {
  const t = {};
  for (const [r, o] of Object.entries(e)) {
    const s = te[r] ?? r;
    t[s] = o;
  }
  return t;
}
async function k({
  countPerPage: e,
  fields: t,
  getPermanentAssetsPaths: r,
  pageNumber: o,
  query: s,
  siteUrl: u,
  sort: a,
  token: p,
  useSession: I
}) {
  const m = t?.map(re);
  try {
    return (await l.request({
      baseURL: u,
      method: "GET",
      params: {
        CountPerPage: e,
        Fields: m,
        Format: "json",
        GetPermanentAssetsPaths: r || void 0,
        PageNumber: o,
        Query: _(s),
        Sort: a || void 0,
        Token: p || void 0,
        UseSession: I || void 0
      },
      paramsSerializer: { indexes: null },
      responseType: "json",
      transformResponse: [
        ...Array.isArray(l.defaults.transformResponse) ? l.defaults.transformResponse : [],
        (n) => ({
          items: (n.APIResponse?.Items ?? []).map(oe),
          sort: n.APIResponse?.GlobalInfo?.Sort ?? "",
          totalCount: n.APIResponse?.GlobalInfo?.TotalCount ?? 0
        })
      ],
      url: x["4.0"]
    })).data;
  } catch {
    return { items: [], sort: "", totalCount: 0 };
  }
}
async function Ie({
  assetId: e,
  extension: t,
  format: r,
  siteUrl: o,
  token: s,
  transformations: u,
  useSession: a
}) {
  try {
    return (await l.request({
      baseURL: o,
      method: "GET",
      params: {
        SourceAssetFormat: r,
        SourceAssetRecordID: e,
        TargetExtension: V(t),
        Token: s || void 0,
        Transformations: u,
        UseSession: a || void 0
      },
      /**
       * https://link.orangelogic.com/Tasks/41S1XH
       */
      timeout: 3e5,
      // 5 minutes
      url: W.GET_TRANSFORM_ASSET_LINK
    })).data;
  } catch {
    return null;
  }
}
const ne = 50;
function se(e, t) {
  const r = [];
  for (let o = 0; o < e.length; o += t)
    r.push(e.slice(o, o + t));
  return r;
}
async function me({
  extraFields: e,
  getPermanentAssetsPaths: t,
  recordIds: r,
  token: o
}) {
  if (!Array.isArray(r) || r.length === 0)
    return { facets: [], items: [], totalCount: 0 };
  const s = e?.filter((n) => n && typeof n == "string") ?? [], u = [
    ...s,
    E,
    y,
    T,
    J,
    ee,
    D
  ], a = se(r, ne), p = await Promise.all(
    a.map(
      (n) => k({
        countPerPage: n.length,
        fields: u,
        getPermanentAssetsPaths: t,
        pageNumber: 1,
        query: { recordId: n },
        token: o
      })
    )
  ), I = new Map(r.map((n, d) => [n, d])), m = p.flatMap((n) => n.items).map((n) => {
    let d = c(n, y);
    return d === "" && (d = c(n, T)), {
      name: d,
      originalUrl: c(n, E),
      recordId: c(n, D),
      ...s.reduce(
        (i, f) => (i[f] = c(n, f), i),
        {}
      )
    };
  }).sort(
    (n, d) => (I.get(n.recordId) ?? 1 / 0) - (I.get(d.recordId) ?? 1 / 0)
  ), A = p.reduce(
    (n, d) => n + d.totalCount,
    0
  );
  return { facets: [], items: m, totalCount: A };
}
function c(e, t) {
  const r = e[t];
  return r == null ? "" : typeof r == "string" ? r : typeof r == "number" || typeof r == "boolean" ? String(r) : q(r) ? r.URI : "";
}
async function Ee({
  countPerPage: e,
  extraFields: t,
  getPermanentAssetsPaths: r,
  limitedDocTypes: o,
  pageNumber: s,
  parentFolderIdentifier: u,
  searchTerm: a,
  sortOrder: p,
  token: I
}) {
  if (!u)
    return { facets: [], items: [], totalCount: 0 };
  const m = (t?.filter((i) => i && typeof i == "string") ?? []).map((i) => i.replace("%20", " ")), A = {
    parentFolderIdentifier: u,
    ...o.length > 0 ? { docType: $.Image } : {}
  }, n = await k({
    countPerPage: e,
    fields: [
      ...m,
      w,
      L,
      E,
      M,
      j,
      U,
      b,
      O,
      v,
      G,
      P,
      D,
      T,
      y
    ],
    getPermanentAssetsPaths: r,
    pageNumber: s,
    query: A,
    sort: void 0,
    token: I
  }), d = n.items.map((i) => {
    let f = c(i, P), h = c(i, y), S = c(i, L);
    f && !f.startsWith(".") && (f = "." + f), h === "" && (h = c(i, T)), f.toLowerCase() === ".gif" && (S = c(i, E));
    const C = c(i, D);
    return {
      docSubType: c(i, v),
      docType: c(i, O) || "",
      extension: f,
      height: c(i, U) || "0",
      id: C,
      identifier: c(i, G),
      imageUrl: S,
      name: h,
      originalUrl: c(i, E),
      recordId: C,
      size: c(i, b) || "0 MB",
      tags: c(i, M),
      width: c(i, j) || "0",
      ...m.reduce(
        (g, N) => (g[N] = c(i, N), g),
        {}
      )
    };
  });
  return {
    facets: [],
    items: d,
    totalCount: n.totalCount
  };
}
async function Ae({
  autoCropMode: e,
  cropHeight: t,
  cropWidth: r,
  imageUrl: o,
  useSession: s
}) {
  try {
    return (await l.request({
      method: "GET",
      params: {
        AutoCropMode: e,
        CropHeight: t,
        CropWidth: r,
        ImageUrl: o && new URL(o, window.location.origin).href,
        UseSession: s || void 0
      },
      responseType: "json",
      timeout: 3e5,
      // 5 minutes
      transformResponse: [
        ...Array.isArray(l.defaults.transformResponse) ? l.defaults.transformResponse : [],
        (a) => ({
          height: a.cropHeight,
          width: a.cropWidth,
          x: a.cropX,
          y: a.cropY
        })
      ],
      url: W.GET_CROP_ZONE_SUGGESTION
    })).data;
  } catch {
    return null;
  }
}
async function _e({
  assetRecordId: e,
  siteUrl: t,
  token: r,
  useSession: o
}) {
  try {
    return (await l.request({
      baseURL: t,
      method: "GET",
      params: {
        RecordId: e,
        Token: r,
        UseSession: o || void 0
      },
      responseType: "json",
      transformResponse: [
        ...Array.isArray(l.defaults.transformResponse) ? l.defaults.transformResponse : [],
        (u) => !u || typeof u != "object" ? [] : u.proxies?.map((a) => ({
          cdnName: a.cdnName,
          extension: a.extension,
          formatHeight: a.formatHeight,
          formatWidth: a.formatWidth,
          height: a.height,
          permanentLink: a.permanentLink,
          proxyLabel: a.proxyLabel,
          proxyName: a.proxyName,
          width: a.width
        })) ?? []
      ],
      url: K
    })).data;
  } catch {
    return [];
  }
}
async function De({
  siteUrl: e
} = {}) {
  try {
    return (await l.request({
      baseURL: e,
      method: "GET",
      responseType: "json",
      transformResponse: [
        ...Array.isArray(l.defaults.transformResponse) ? l.defaults.transformResponse : [],
        (r) => !r || typeof r != "object" ? {
          formatsByDocType: {
            Audio: {},
            Image: {},
            Multimedia: {},
            Video: {}
          }
        } : {
          formatsByDocType: r.formatsByDocType ?? {}
        }
      ],
      url: B
    })).data;
  } catch {
    return { formatsByDocType: {} };
  }
}
export {
  L as D,
  D as F,
  E as O,
  me as a,
  Ie as b,
  Ae as c,
  De as d,
  k as e,
  Ee as f,
  U as g,
  j as h,
  q as i,
  P as j,
  G as k,
  _e as l,
  O as m,
  b as n,
  v as o
};
