/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { s as p, c as A, e as d } from "./cardsHelpers.js";
import * as c from "@esri/solution-common";
import { a as D, g as v, c as E, b, d as I, e as J } from "./helpers.js";
import "@esri/arcgis-rest-portal";
class j {
  /**
   * 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, a) {
    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 = a, this.anonAgolSession = new c.UserSession({}), this.agolPortalUrl = D(a);
  }
  /**
   * 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 isEnterprise When true we are working with an enterprise portal
   * @param signal AbortController signal
   * @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, a, e, h, m, s, o) {
    const C = s?.start ? s.start : 1, g = s?.num ? s.num : 24, R = this.portalUrl + "/sharing/rest", B = this.agolPortalUrl + "/sharing/rest", T = 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 = p(
      this.cardCache,
      this.cardCacheParams.sortField,
      this.cardCacheParams.sortOrder
    )), this.cardCache.length > 0) {
      let i;
      if (o && o.size > 0) {
        const n = A(this.cardCache, o);
        i = d(n, C, g);
      } else
        i = d(this.cardCache, C, g);
      return Promise.resolve(i);
    }
    const F = {
      filter: r.filter,
      sortField: r.sortField,
      sortOrder: r.sortOrder,
      categories: r?.categories ? this.convertSearchCategories(r.categories) : "",
      signal: m
    }, f = [];
    if (t && !h) {
      const i = e || new c.UserSession({});
      f.push(
        c.searchGroupAllContents(
          t,
          r.q,
          i,
          F,
          R
        )
      );
    }
    return a && h && f.push(
      c.searchGroupAllContents(
        a,
        r.q,
        T,
        F,
        B
      )
    ), Promise.allSettled(f).then((i) => {
      const n = [];
      i.forEach((l) => {
        if (l.status === "fulfilled") {
          const O = l.value;
          let S = "", w = !1;
          S = this.agolPortalUrl, w = !0, O.results.forEach((u) => {
            u.sourcePortalUrl = S, u.knownToBePublicSource = w;
          }), n.push(O);
        } else if (l.status === "rejected")
          throw new Error(
            l.reason.message ? l.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
          );
      }), n.length === 0 ? this.cardCache = [] : n.length === 1 ? this.cardCache = this.getCardsFromResponse(n[0]) : this.cardCache = p(
        this.getCardsFromResponse(this.mergeResponses(n)),
        this.cardCacheParams.sortField,
        this.cardCacheParams.sortOrder
      );
      let P;
      if (o && o.size > 0) {
        const l = A(this.cardCache, o);
        P = d(l, C, g);
      } else
        P = d(this.cardCache, C, g);
      return Promise.resolve(P);
    }).catch((i) => Promise.reject(new Error(i.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, a = "", e) {
    const h = this.portalUrl + "/sharing/rest";
    if (e.aborted)
      return Promise.resolve([]);
    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 = p(
      this.cardCache,
      this.cardCacheParams.sortField,
      this.cardCacheParams.sortOrder
    )), e.aborted)
      return Promise.resolve([]);
    if (this.cardCache.length > 0) {
      const s = d(this.cardCache, 1, this.cardCache.length);
      return Promise.resolve(s);
    }
    const m = {
      q: r.q,
      filter: r.filter,
      sortField: r.sortField,
      sortOrder: r.sortOrder,
      authentication: t,
      portal: h,
      categories: r?.categories ? JSON.stringify(r.categories) : "",
      num: r.num,
      signal: e
    };
    return a ? c.getItemBase(a, t).then((s) => {
      if (e.aborted)
        return Promise.resolve([]);
      this.cardCache = this.getCardsFromResponse({ results: [s] });
      const o = d(this.cardCache, 1, this.cardCache.length);
      return Promise.resolve(o);
    }).catch((s) => Promise.reject(new Error(s))) : c.searchAllItems(m).then((s) => {
      this.cardCache = this.getCardsFromResponse(s);
      const o = d(this.cardCache, 1, this.cardCache.length);
      return Promise.resolve(o);
    }).catch((s) => Promise.reject(new Error(s)));
  }
  // ---------------------------------------------------------------------------------------------------------------- //
  /**
   * 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 ? c.sanitizeJSON(r.results).map(
      (e) => {
        const h = e.sourcePortalUrl ? e.sourcePortalUrl : this.portalUrl, m = e.sourcePortalUrl ? e.sourcePortalUrl : this.orgUrl, s = {
          id: e.id,
          title: e.title,
          snippet: e.snippet || "",
          description: e.description || "",
          url: e.url || "",
          itemUrl: `${m}/home/item.html` + J([{ k: "id", v: e.id }]) || "",
          thumbnailFilename: e.thumbnail,
          thumbnailUrl: I(
            e.id,
            e.thumbnail,
            this.cMissingImageDataURI,
            h
          ),
          tryitUrl: e.url || "",
          typeKeywords: e.typeKeywords,
          learnMoreUrl: e.properties?.learnMoreUrl || "",
          createdMs: e.created,
          created: b(e.created, this.locale),
          modified: b(e.modified, this.locale),
          numViews: e.numViews,
          tags: e.tags,
          categories: e.groupCategories && e.groupCategories.length > 0 ? e.groupCategories : e.categories || [],
          licenseInfo: E(e.licenseInfo),
          deployCommonId: v(e.typeKeywords || [], "solutionid-"),
          deployVersion: v(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, h),
          sourcePortalUrl: e.sourcePortalUrl || "",
          knownToBePublicSource: e.knownToBePublicSource || !1,
          waitId: "",
          relatedSolutions: c.getProp(e, "properties.relatedSolutions") || [],
          owner: e.owner
        };
        return s.deployCommonId !== "" && s.deployVersion !== "" ? s : 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 a = [];
    return r.forEach((e) => a = a.concat(e.results)), {
      query: r[0].query,
      start: 1,
      num: t,
      nextStart: -1,
      total: t,
      results: a
    };
  }
  /**
   * 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, a) {
    return t ? t.map(
      (e) => (e.format === "image" && (e.name = a + "/sharing/rest/content/items/" + r + "/resources/" + e.name), e)
    ) : [];
  }
}
export {
  j as C
};
