import{filter as t}from"@arcgis/core/core/promiseUtils.js";import*as e from"@arcgis/core/geometry/operators/intersectsOperator.js";import{Feature as r}from"../data/Feature.js";import{project as a}from"../utilities/geometry.js";import{isGraphic as i}from"./esri.js";const o="alasql-id",s={outFields:["*"],returnGeometry:!0};export async function query(t,e,r,a){if(!r?.length)return[];const{spatialFilter:l,returnGeometry:u,outFields:p}={...s,...a},c=l?await spatialFilter(r,l):r,m=!i(c[0]);if(t){const r=new Map,a=c.map(((t,e)=>{r.set(e,t);let a={};return m?Array.from(t.attributes.entries()).forEach((([t,e])=>{a[t]=e})):a={...t.attributes},a[o]=e,a}));return(0,(await import("alasql")).default)(`SELECT * FROM ? WHERE ${t}`,[a]).map((t=>m?r.get(t[o]):n(t,r.get(t[o]),e,u,p)))}return m?c:c.map((t=>n(t.attributes,t,e,u,p)))}export async function count(t,e,r){if(!e?.length)return 0;const{spatialFilter:a}=r??{},s=a?await spatialFilter(e,a):e,n=!i(s[0]);if(t){const e=s.map(((t,e)=>{let r={};return n?Array.from(t.attributes.entries()).forEach((([t,e])=>r[t]=e)):r={...t.attributes},r[o]=e,r}));return(0,(await import("alasql")).default)(`SELECT * FROM ? WHERE ${t}`,[e]).length}return s.length}export async function spatialFilter(r,i){if(!r?.length)return[];const o=r[0]?.geometry?.spatialReference;let s=i.clone();return o&&!o.equals(s.spatialReference)&&(s=(await a([s],o))[0]),t(r,(async t=>!!t.geometry&&e.execute(s,t.geometry)))}function n(t,e,a,i,s){const n=new r({source:a});for(const e of Object.keys(t))e!==o&&(s.includes("*")||s.includes(e))&&n.attributes.set(e,t[e]);return i&&(n.geometry=e.geometry??void 0),e.popupTemplate&&(n.settings.popupTemplate=e.popupTemplate),n}