/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
import e from"../../Viewpoint.js";import t from"../../core/Error.js";import r from"../../core/Logger.js";import{geographicToWebMercator as o}from"../../geometry/support/webMercatorUtils.js";import n from"../../portal/Portal.js";import{createForItemRead as i}from"../../portal/support/jsonContext.js";import{project as a}from"../../rest/geometryService/project.js";import s from"../../rest/support/ProjectParameters.js";function p(e,t){return t.resourceInfo?l(t,t.resourceInfo,{origin:e.origin}):t.portalItem?.id?c(e,t,t.portalItem):Promise.resolve()}function l(e,t,r){const o={context:{...r,layerContainerType:"operational-layers"}};return e.portalItem&&(o.context.portal=e.portalItem.portal||n.getDefault()),import("../../layers/support/layersCreator.js").then(({populateOperationalLayers:r})=>{const n=[],i=t.operationalLayers;i?.length&&n.push(r(e.layers,i,o));const a={...o,context:{...o.context,layerContainerType:"tables"},defaultLayerType:"ArcGISFeatureLayer"},s=t.tables;return s?.length&&n.push(r(e.tables,s,a)),Promise.allSettled(n).then(()=>{})})}async function c(e,o,n){if(await n.load().catch(r=>{throw new t(`${e.name}:load-portal-item`,"Failed to load portal item",{error:r})}),n.type!==e.itemType)throw new t(`${e.name}:invalid-portal-item`,`Invalid portal item type '${n.type}', expected '${e.itemType}'`,{type:n.type});const a=await n.fetchData();o.resourceInfo=a;const s=i(n,e.origin);await m(e,o,a,s),o.resourceReferences={portalItem:n,paths:s.readResourcePaths};const p=await f(o.initialViewProperties,n,r.getLogger(o));if(p){const t=o.initialViewProperties?.clone()??e.createInitialViewProperties();t.viewpoint=p,o.initialViewProperties=t}}function m(e,t,r,o){const n=u(e,r);return t.read(n,o),l(t,n,o)}function u(e,t){const r=e.parseVersion(t.version||"",e.name);return e.currentVersion.validate(r),t.version=`${r.major}.${r.minor}`,t}async function f(t,r,o){const n=t?.viewpoint?.targetGeometry;if(n)return null;const i=await y(t,r,o);if(!i)return null;return new e({targetGeometry:i})}async function y(e,t,r){const n=e?.spatialReference,i=t?.extent;if(!n||!i)return null;if(n.isWGS84)return i.clone();if(n.isWebMercator)return o(i);const{getGeometryServiceURL:p}=await import("../../portal/support/geometryServiceUtils.js");try{const e=await p(t),r=new s({geometries:[i],outSpatialReference:n});return(await a(e,r))[0]}catch(l){r.error("Error projecting item's extent:",l)}return null}export{p as loadFromSource};
