/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { s as O, d as D, e as m, b as I } from "./cardsHelpers.js";
import * as h from "@esri/solution-common";
import { d as b, g as B, e as T, f as E, i as y, j as M } from "./helpers.js";
import { B as N } from "./interfaces.js";
class x {
  /**
   * Constructor
   *
   * @param orgUrl URL of organization, e.g., "http://myOrg.maps.arcgis.com"
   * @param portalUrl URL of portal, e.g., "https://www.arcgis.com"
   * @param userSession Authentication
   */
  constructor(r, t, s) {
    this.cMissingImageDataURI = "https://static.arcgis.com/images/solution.png", this.cardCache = [], this.cardCacheParams = {
      q: "",
      categoriesAsStr: "[]",
      sortField: "title",
      sortOrder: "asc"
    }, this.locale = r, this.orgUrl = t, this.portalUrl = s, this.anonAgolSession = new h.UserSession({}), this.agolPortalUrl = b(s);
  }
  /**
   * Adds a card to the cache to keep cache fresh between full refreshes.
   *
   * @param card Card to add
   */
  addToCache(r) {
    this.cardCache.push(r);
  }
  /**
   * Returns the current cache.
   *
   * @returns Cards in the cache
   */
  getCache() {
    return this.cardCache;
  }
  /**
   * Removes a card to the cache to keep cache fresh between full refreshes.
   *
   * @param id Id of card to remove
   */
  removeFromCache(r) {
    this.cardCache = this.cardCache.filter((t) => t.id !== r);
  }
  /**
   * Fetches cards for availale Solutions from the server.
   *
   * @param query AGO query terms and options
   * @param primarySolutionsGroupId Id of a group that's the primary source of Solutions for AGO or Enterprise
   * @param agoBasedEnterpriseSolutionsGroupId Id of an AGO-based set of Enterprise Solutions
   * @param userSession Authentication for thumbnailUrl
   * @param pagingParams Parameters for how the request is to be batched
   * @param acceptableIds A set of item ids that the results must be a part of; if not defined, then there's no restriction
   * @returns A promise resolving to a collection of available Solutions as cards as well as paging information about
   * where those cards came from in the fetcher cache; in case of failure, the promise resolves to an error message
   */
  requestAvailableSolutionCards(r, t, s, e, i, a, o) {
    const g = a?.start ? a.start : 1, C = a?.num ? a.num : 24, p = this.portalUrl + "/sharing/rest", P = this.agolPortalUrl + "/sharing/rest", f = this.anonAgolSession, u = JSON.stringify(r.categories);
    if (this.cardCacheParams.q !== r.q || this.cardCacheParams.categoriesAsStr !== u || r.sortField === "relevance" ? (this.cardCache = [], this.cardCacheParams = {
      q: r.q,
      categoriesAsStr: u,
      sortField: r.sortField,
      sortOrder: r.sortOrder
    }) : (this.cardCacheParams.sortField !== r.sortField || this.cardCacheParams.sortOrder !== r.sortOrder) && (this.cardCacheParams.sortField = r.sortField, this.cardCacheParams.sortOrder = r.sortOrder, this.cardCache = O(
      this.cardCache,
      this.cardCacheParams.sortField,
      this.cardCacheParams.sortOrder
    )), this.cardCache.length > 0) {
      let c;
      if (o && o.size > 0) {
        const l = D(this.cardCache, o);
        c = m(l, g, C);
      } else
        c = m(this.cardCache, g, C);
      return Promise.resolve(c);
    }
    const F = {
      filter: r.filter,
      sortField: r.sortField,
      sortOrder: r.sortOrder,
      categories: r?.categories ? this.convertSearchCategories(r.categories) : ""
    }, S = [];
    if (t && !i) {
      const c = e || new h.UserSession({});
      S.push(
        h.searchGroupAllContents(
          t,
          r.q,
          c,
          F,
          p
        )
      );
    }
    return s && i && S.push(
      h.searchGroupAllContents(
        s,
        r.q,
        f,
        F,
        P
      )
    ), Promise.allSettled(S).then((c) => {
      const l = [];
      c.forEach((d) => {
        if (d.status === "fulfilled") {
          const w = d.value;
          let A = "", v = !1;
          A = this.agolPortalUrl, v = !0, w.results.forEach((R) => {
            R.sourcePortalUrl = A, R.knownToBePublicSource = v;
          }), l.push(w);
        } else if (d.status === "rejected")
          throw new Error(
            d.reason.message ? d.reason.message : "cannotAccessAGO"
            // (isPrimary
            // // A failed fetch of the primary group in enterprise or AGO
            // ? result.reason.message
            // // We're in enterprise and configured to search AGO (because agoBasedEnterpriseSolutionsGroupId
            // // is defined), but appear not to be able to reach the internet
            // : "enterpriseCannotAccessAGO"
            // ) as string
          );
      }), l.length === 0 ? this.cardCache = [] : l.length === 1 ? this.cardCache = this.getCardsFromResponse(l[0]) : this.cardCache = O(
        this.getCardsFromResponse(this.mergeResponses(l)),
        this.cardCacheParams.sortField,
        this.cardCacheParams.sortOrder
      );
      let U;
      if (o && o.size > 0) {
        const d = D(this.cardCache, o);
        U = m(d, g, C);
      } else
        U = m(this.cardCache, g, C);
      return Promise.resolve(U);
    }).catch((c) => Promise.reject(new Error(c.message)));
  }
  /**
   * Fetches cards for deployed Solutions from the server.
   *
   * @param query AGO query terms and options
   * @param userSession Authentication for thumbnailUrl
   * @returns A collection of deployed Solutions as cards; the paging information shows that all of the cards
   * are returned
   */
  requestDeployedSolutionCards(r, t, s = "") {
    const e = this.portalUrl + "/sharing/rest";
    if (this.cardCacheParams.q !== r.q || this.cardCacheParams.categoriesAsStr !== JSON.stringify(r.q) || r.sortField === "relevance" ? (this.cardCache = [], this.cardCacheParams = {
      q: r.q,
      categoriesAsStr: "[]",
      sortField: r.sortField,
      sortOrder: r.sortOrder
    }) : (this.cardCacheParams.sortField !== r.sortField || this.cardCacheParams.sortOrder !== r.sortOrder) && (this.cardCacheParams.sortField = r.sortField, this.cardCacheParams.sortOrder = r.sortOrder, this.cardCache = O(
      this.cardCache,
      this.cardCacheParams.sortField,
      this.cardCacheParams.sortOrder
    )), this.cardCache.length > 0) {
      const a = m(this.cardCache, 1, this.cardCache.length);
      return Promise.resolve(a);
    }
    const i = {
      q: r.q,
      filter: r.filter,
      sortField: r.sortField,
      sortOrder: r.sortOrder,
      authentication: t,
      portal: e,
      categories: r?.categories ? JSON.stringify(r.categories) : ""
    };
    return s ? h.getItemBase(s, t).then((a) => {
      this.cardCache = this.getCardsFromResponse({ results: [a] });
      const o = m(this.cardCache, 1, this.cardCache.length);
      return Promise.resolve(o);
    }).catch((a) => Promise.reject(new Error(a))) : h.searchAllItems(i).then((a) => {
      this.cardCache = this.getCardsFromResponse(a);
      const o = m(this.cardCache, 1, this.cardCache.length);
      return Promise.resolve(o);
    }).catch((a) => Promise.reject(new Error(a)));
  }
  // ---------------------------------------------------------------------------------------------------------------- //
  /**
   * Stringifies categories for search.
   *
   * @param categories AGO item categories, e.g., "/Categories/Conservation"
   * or ["/Categories/Conservation", "/Categories/Pipeline"]
   * @returns Categories where each element is a stringified array of categories
   */
  convertSearchCategories(r) {
    return r && (Array.isArray(r) ? r = r.map(
      (t) => JSON.stringify(Array.isArray(t) ? t : [t])
      // force to an array to allow categories with commas
    ) : r = JSON.stringify([r])), r;
  }
  /**
   * Constructs Solution cards from a Solution-query response.
   *
   * @param response Response from a query
   * @returns Solution information as cards
   */
  getCardsFromResponse(r) {
    return r.results.length > 0 ? h.sanitizeJSON(r.results).map(
      (e) => {
        const i = e.sourcePortalUrl ? e.sourcePortalUrl : this.portalUrl, a = e.sourcePortalUrl ? e.sourcePortalUrl : this.orgUrl, o = {
          id: e.id,
          title: e.title,
          snippet: e.snippet || "",
          description: e.description || "",
          url: e.url || "",
          itemUrl: `${a}/home/item.html` + M([{ k: "id", v: e.id }]) || "",
          thumbnailFilename: e.thumbnail,
          thumbnailUrl: y(
            e.id,
            e.thumbnail,
            this.cMissingImageDataURI,
            i
          ),
          tryitUrl: e.url || "",
          typeKeywords: e.typeKeywords,
          learnMoreUrl: e.properties?.learnMoreUrl || "",
          createdMs: e.created,
          created: E(e.created, this.locale),
          modified: E(e.modified, this.locale),
          numViews: e.numViews,
          tags: e.tags,
          categories: e.groupCategories && e.groupCategories.length > 0 ? e.groupCategories : e.categories || [],
          licenseInfo: T(e.licenseInfo),
          deployCommonId: B(e.typeKeywords || [], "solutionid-"),
          deployVersion: B(e.typeKeywords || [], "solutionversion-"),
          canDelete: e.created > 16183314e5,
          // Only solutions deployed after April 13, 2021 at 9:30PM can be deleted (9.1 release)
          preview: this.preparePreviewImageUrls(e.id, e.properties?.preview, i),
          sourcePortalUrl: e.sourcePortalUrl || "",
          knownToBePublicSource: e.knownToBePublicSource || !1,
          waitId: "",
          relatedSolutions: h.getProp(e, "properties.relatedSolutions") || [],
          owner: e.owner
        };
        return o.deployCommonId !== "" && o.deployVersion !== "" ? o : null;
      }
    ).filter((e) => e != null) : [];
  }
  /**
   * Merge a set of search responses into a single response item.
   *
   * @param responseSet Array of search results
   * @returns A response item that takes its query from the first item in the set and sets the other properties
   * as if all of the responses are the result of one, large query that's independent of AGO's 100-item limit.
   */
  mergeResponses(r) {
    let t = 0;
    r.forEach((e) => t += e.total);
    let s = [];
    return r.forEach((e) => s = s.concat(e.results)), {
      query: r[0].query,
      start: 1,
      num: t,
      nextStart: -1,
      total: t,
      results: s
    };
  }
  /**
   * Converts image preview information into a URL pointing to that image; returns non-image previews unchanged.
   *
   * @param id Item id to insert into URL
   * @param preview List of previews to modify
   * @returns Copy of previews with iamge previews modified
   */
  preparePreviewImageUrls(r, t, s) {
    return t ? t.map(
      (e) => (e.format === "image" && (e.name = s + "/sharing/rest/content/items/" + r + "/resources/" + e.name), e)
    ) : [];
  }
}
async function z(n, r, t, s, e = N, i = "created", a = "desc", o = !1, g = [], C = [], p, P) {
  if (!n?.IsSignedIn)
    return;
  const f = {
    q: e,
    filter: "type:Solution",
    sortField: i,
    sortOrder: a,
    delay: o,
    categories: g
  };
  return f.q += J(n, p), await j(
    r,
    f,
    s,
    C,
    P
  );
}
function J(n, r) {
  let t = "";
  const s = n.PortalUserOrg, e = n.PortalUserName;
  return s && (t += " orgid:" + s), r !== "My organization's solutions" && e && (t += " owner:" + e), t;
}
async function j(n, r, t, s, e = "") {
  const i = await t.requestDeployedSolutionCards(r, n, e), a = I(i.cards, s);
  return {
    cards: i.cards,
    relatedSolutions: a
  };
}
export {
  x as C,
  z as g
};
