/* COPYRIGHT Esri - https://js.arcgis.com/5.1.2/LICENSE.txt */
import{id as e}from"../../kernel.js";import r from"../../request.js";import t from"../../core/Error.js";import{throwIfAbortError as n}from"../../core/promiseUtils.js";import{parse as a}from"./arcgisLayerUrl.js";import o from"../../portal/Portal.js";import i from"../../portal/PortalItem.js";async function s(e,r){const n=a(e);if(!n)throw new t("invalid-url","Invalid scene service url");const o={...r,sceneServerUrl:n.url.path,layerId:n.sublayer??void 0};if(o.sceneLayerItem??=await l(o),null==o.sceneLayerItem)return f(o.sceneServerUrl.replace("/SceneServer","/FeatureServer"),o);const i=await y(o);if(!i?.url)throw new t("related-service-not-found","Could not find feature service through portal item relationship");o.featureServiceItem=i;const s=await f(i.url,o);return s.portalItem=i,s}async function l(e){const r=(await c(e)).serviceItemId;if(!r)return null;const t=new i({id:r,apiKey:e.apiKey}),a=await u(e);null!=a&&(t.portal=new o({url:a}));try{return await t.load({signal:e.signal})}catch(s){return n(s),null}}async function c(e){if(e.rootDocument)return e.rootDocument;const t={query:{f:"json",...e.customParameters,token:e.apiKey},responseType:"json",signal:e.signal};try{const n=await r(e.sceneServerUrl,t);e.rootDocument=n.data}catch{e.rootDocument={}}return e.rootDocument}async function u(t){const a=e?.findServerInfo(t.sceneServerUrl);if(a?.owningSystemUrl)return a.owningSystemUrl;const o=t.sceneServerUrl.replace(/(.*\/rest)\/.*/i,"$1")+"/info";try{const e=(await r(o,{query:{f:"json"},responseType:"json",signal:t.signal})).data.owningSystemUrl;if(e)return e}catch(i){n(i)}return null}async function f(e,n){const o=a(e);if(!o)throw new t("invalid-feature-service-url","Invalid feature service url");const i=o.url.path,s=n.layerId;if(null==s)return{serverUrl:i};const l=c(n),u=n.featureServiceItem?await n.featureServiceItem.fetchData("json"):null,f=(u?.layers?.[0]||u?.tables?.[0])?.customParameters,y=e=>{const t={query:{f:"json",...f},responseType:"json",authMode:e,signal:n.signal};return r(i,t)},m=y("anonymous").catch(()=>y("no-prompt")),[p,d]=await Promise.all([m,l]),v=d?.layers,w=p.data&&p.data.layers;if(!Array.isArray(w))throw new Error("expected layers array");if(Array.isArray(v))for(let r=0;r<Math.min(v.length,w.length);r++){if(v[r].id===s)return{serverUrl:i,layerId:w[r].id}}else if(null!=s&&s<w.length)return{serverUrl:i,layerId:w[s].id};throw new Error("could not find matching associated sublayer")}async function y({sceneLayerItem:e,signal:r}){if(!e)return null;try{const t=(await e.fetchRelatedItems({relationshipType:"Service2Service",direction:"reverse"},{signal:r})).find(e=>"Feature Service"===e.type)||null;if(!t)return null;const n=new i({portal:t.portal,id:t.id});return await n.load(),n}catch(t){return n(t),null}}export{s as findAssociatedFeatureService};
