import e from"@arcgis/core/core/Collection";import{RelationshipCollection as i}from"../data/FeatureSourceBase.js";import{ArcGISRelationship as r}from"../tasks/query/ArcGISRelationship.js";import{map as t}from"../utilities/promise.js";import{DefaultArcGISRequestHelper as s}from"./ArcGISRequestHelper.js";export class ArcGISRelationshipCollection extends i{_unresolvedRelationships=new e;_requestHelper;_initializePromise;get requestHelper(){return this._requestHelper||(this._requestHelper=this._source.requestHelper??new s),this._requestHelper}set requestHelper(e){this._requestHelper=e}async initialize(){return void 0===this._initializePromise&&(this._initializePromise=(async()=>{if(!this._sourceUrl)return;const e=await this.requestHelper.request(this._sourceUrl,{query:{f:"json"}});e?.data?.relationships&&await t(e.data.relationships,(async e=>{const i=`${this._sourceUrl.slice(0,this._sourceUrl.length-`${this._sourceLayerId}`.length-1)}/${e.relatedTableId}`,r=await this.requestHelper.request(i,{query:{f:"json"}});if(!r?.data||!Array.isArray(r?.data.relationships))return;const t=r.data.relationships.find((e=>e.relatedTableId===this._sourceLayerId));if(!t)return;let s="many-to-many";switch(e.cardinality){case"esriRelCardinalityOneToOne":s="one-to-one";break;case"esriRelCardinalityOneToMany":s="esriRelRoleOrigin"===e.role?"one-to-many":"many-to-one";break;case"esriRelCardinalityManyToMany":s="many-to-many";break;default:throw new Error(`Unknown cardinality value "${e.cardinality}".`)}this._unresolvedRelationships.add({$relationshipType:"ArcGISRelationship",id:`${e.id}`,title:e.name,keyField:e.keyField,relatedKeyField:t.keyField,relatedSource:void 0,relatedLayerId:e.relatedTableId,cardinality:s,relationshipTableId:e.relationshipTableId,originForeignKey:e.keyFieldInRelationshipTable,destinationForeignKey:t.keyFieldInRelationshipTable})}))})()),this._initializePromise}get _collection(){const e=this._unresolvedRelationships.toArray();this._unresolvedRelationships.removeAll();for(const i of e)this._resolveRelationship(i)||this._unresolvedRelationships.add(i);return this._collectionField}_resolveRelationship(e){const i=this._findRelatedSource(e.relatedLayerId);return!!i&&(e.relatedSource=i,this.add(new r(e)),!0)}}