/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import * as common from "@esri/solution-common";
import "@arcgis/core/intl.js";
import { I as ITEM_TITLE_LENGTH } from "./interfaces.js";
function addParams(paramPairs) {
  let paramString = "";
  let sep = "?";
  paramPairs.forEach((paramPair) => {
    if (paramPair.k && paramPair.v) {
      paramString += sep + paramPair.k + "=" + paramPair.v;
      sep = "&";
    }
  });
  return paramString;
}
function checkVelocitySupport(userSession) {
  if (userSession) {
    return common.getVelocityUrlBase(userSession, {}).then((velocityUrl) => {
      return Promise.resolve(!!velocityUrl);
    });
  } else {
    return Promise.resolve(false);
  }
}
async function checkConflictingNames(nameToCheck, userSession) {
  const auth = userSession;
  const username = await auth.getUsername();
  const query = new common.SearchQueryBuilder().match(nameToCheck).in("title").and().match(username).in("owner");
  const searchOptions = {
    q: query,
    filter: "type:Solution",
    authentication: auth
  };
  const response = await common.searchAllItems(searchOptions);
  const itemTitles = response.results.map((item) => item.title);
  const { folders } = await common.getFoldersAndGroups(auth);
  const folderTitles = folders.map((folder) => folder.title);
  const allNames = [...itemTitles, ...folderTitles].map((name) => name.trim().toLowerCase());
  const lowerBase = nameToCheck.toLowerCase();
  const conflictingNames = allNames.filter((name) => name === lowerBase);
  const similiarNames = allNames.filter((name) => name.startsWith(lowerBase));
  return { conflictingNames, similiarNames };
}
async function validateSolutionName(proposedName, userSession) {
  if (isNameEmpty(proposedName)) {
    return { status: false, type: "empty" };
  }
  if (isLengthExceeded(proposedName)) {
    return { status: false, type: "exceed length" };
  }
  if (hasInvalidChars(proposedName, "folder")) {
    return { status: false, type: "special character" };
  }
  const hasNameConflicts = await checkConflictingNames(proposedName.trim(), userSession);
  if (hasNameConflicts.conflictingNames.length > 0) {
    return { status: false, type: "not unique" };
  }
  return { status: true, type: "" };
}
function isNameEmpty(proposedName) {
  return proposedName.length <= 0;
}
function isLengthExceeded(proposedName) {
  return proposedName.length > ITEM_TITLE_LENGTH;
}
function hasInvalidChars(proposedName, type) {
  const regEx = type === "item" ? /[><~`$^+=|]/u : /[/<>]/u;
  return regEx.test(proposedName);
}
function createDivHtml(content) {
  if (content) {
    const htmlString = content.trim();
    if (htmlString) {
      return "<div>" + htmlString + "</div>";
    } else {
      return "";
    }
  } else {
    return "";
  }
}
function createUrlParams(paramPairs) {
  let paramString = "";
  let sep = "?";
  paramPairs.forEach((paramPair) => {
    if (paramPair.k && paramPair.v) {
      paramString += sep + paramPair.k + "=" + paramPair.v;
      sep = "&";
    }
  });
  return paramString;
}
function generateThumbnailUrl(solutionId, thumbnailFileName, fallBackUrl, portalUrl) {
  let thumbnailUrl = "";
  if (thumbnailFileName) {
    thumbnailUrl = portalUrl + "/sharing/rest/content/items/" + solutionId + "/info/" + thumbnailFileName + createUrlParams([{ k: "w", v: "400" }]);
  } else {
    thumbnailUrl = fallBackUrl;
  }
  return thumbnailUrl;
}
function getAnonymousPortalUrl(authPortalUrl) {
  const h = authPortalUrl ? authPortalUrl.replace("https://", "").replace("www.", "") : "";
  if (h.endsWith("devext.arcgis.com")) {
    return authPortalUrl ?? "https://www.arcgis.com";
  } else if (h.endsWith("mapsqa.arcgis.com") || h.endsWith("qaext.arcgis.com")) {
    return authPortalUrl ?? "https://www.arcgis.com";
  } else {
    return "https://www.arcgis.com";
  }
}
function getDefaultExtent(wkid, srs, defaultExtent) {
  srs.some((sr) => {
    if (sr.wkid === wkid) {
      defaultExtent = sr.defaultExtent;
      return true;
    } else {
      return false;
    }
  });
  return defaultExtent;
}
function getEnvironment(docHost, authHost) {
  if (authHost) {
    return _getEnvironment(authHost);
  } else {
    return _getEnvironment(docHost);
  }
}
function getLocaleLongDateString(timestamp, locale = "en") {
  const converter = new Intl.DateTimeFormat(locale, {
    "year": "numeric",
    "month": "long",
    "day": "numeric"
  });
  const dateString = converter.format(timestamp);
  return dateString;
}
function getTypeKeywordProp(keywords, prefix) {
  let prop = "";
  keywords.some((kw) => {
    if (kw.startsWith(prefix)) {
      prop = kw.substring(prefix.length);
      return true;
    }
    return false;
  });
  return prop;
}
function _getEnvironment(hostname) {
  const h = hostname.replace("www.", "");
  if (h.endsWith("devext.arcgis.com")) {
    return "dev";
  } else if (h.endsWith("mapsqa.arcgis.com") || h.endsWith("qaext.arcgis.com")) {
    return "qa";
  } else if (h === "arcgis.com" || h.endsWith(".arcgis.com")) {
    return "prod";
  } else {
    return "dev";
  }
}
function getEnabledLayerIds(layers, layerOrder) {
  let enabledLayerIds = layers?.reduce((prev, cur) => {
    if (prev.indexOf(cur.id) < 0) {
      prev.push(cur.id);
    }
    return prev;
  }, []) || [];
  return layerOrder ? enabledLayerIds.sort((a, b) => layerOrder.indexOf(a) - layerOrder.indexOf(b)) : enabledLayerIds;
}
function toTitleCase(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}
function getSortTypeDisplayName(sortType) {
  const sortTypeMap = {
    "relevance": "Relevance",
    "title": "Title",
    "new": "New",
    "created": "Date deployed",
    "updated": "Updated",
    "suggested": "Suggested for you"
  };
  return sortTypeMap[sortType] || sortType;
}
function extractErrorMessage(error) {
  if (!error) {
    return "Unknown error";
  }
  if (error.message) {
    return error.message;
  }
  try {
    const serialized = JSON.stringify(error);
    if (serialized && serialized !== "{}") {
      return serialized;
    }
    return error.toString();
  } catch (e) {
    return error.toString();
  }
}
function calculateDuration(startTime) {
  if (!startTime) return 0;
  return parseFloat(((Date.now() - startTime) / 1e3).toFixed(2));
}
export {
  addParams as a,
  getEnabledLayerIds as b,
  getSortTypeDisplayName as c,
  getAnonymousPortalUrl as d,
  createDivHtml as e,
  getLocaleLongDateString as f,
  getTypeKeywordProp as g,
  hasInvalidChars as h,
  generateThumbnailUrl as i,
  createUrlParams as j,
  checkVelocitySupport as k,
  calculateDuration as l,
  extractErrorMessage as m,
  getEnvironment as n,
  getDefaultExtent as o,
  checkConflictingNames as p,
  toTitleCase as t,
  validateSolutionName as v
};
