import{isLayerExtension as e,isSublayerExtension as t}from"../ItemType.js";import{toFeature as n}from"../data/Feature.js";import{isTimeAwareLayer as i}from"../utilities/_layers.js";import{checkArg as s}from"../utilities/checkArg.js";import{cancelifyWithAbortSignal as r}from"./Cancellable.js";export function concatenateWhereClauses(e,t){return e?.length>0&&t?.length>0?`(${e}) and (${t})`:e||t}export function executeQuery(e,t,i,o){return s("query",e).isNotMissing(),s("source",t).isNotMissing(),s("queryable",i).isNotMissing(),e.where=concatenateWhereClauses(i.definitionExpression,e.where),"function"!=typeof t&&constrainQueryTimeExtentToView(e,t),async function*(){const s=e.num;let a=(await r((async t=>i.queryFeatures(e,{signal:t})),o)).features;s>0&&a.length>s&&(a=a.slice(0,s)),yield*a.map((e=>n(e,{source:"function"==typeof t?t(e):t})))}()}export async function executeCount(e,t,n,i){s("query",e).isNotMissing(),s("source",t).isNotMissing(),s("queryable",n).isNotMissing(),e.where=concatenateWhereClauses(n.definitionExpression,e.where),constrainQueryTimeExtentToView(e,t);const o=e.num;e.num=void 0;let a=await r((async t=>n.queryFeatureCount(e,{signal:t})),i);return o>0&&a>o&&(a=o),{source:t,count:a}}export async function executeCountByQuery(e,t,n,i){s("query",e).isNotMissing(),s("source",t).isNotMissing(),s("queryable",n).isNotMissing(),e.where=concatenateWhereClauses(n.definitionExpression,e.where),constrainQueryTimeExtentToView(e,t);const o=e.num;let a=(await r((async t=>n.queryFeatures(e,{signal:t})),i)).features.length;return o>0&&a>o&&(a=o),{source:t,count:a}}export function constrainQueryTimeExtentToView(n,s){let r;if(e(s)?r=s:t(s)&&(r=s.layerExtension),!i(r?.layer))return;const{layer:o,mapExtension:a}=r,u=a?._allLayerViews.find((e=>e.layer===o))?.view?.timeExtent;if(n.timeExtent||(n.timeExtent=o.timeExtent?.clone()),o.useViewTime&&u)if(n.timeExtent){const e=[n.timeExtent.start?.valueOf(),u.start?.valueOf()].filter((e=>!!e)),t=[n.timeExtent.end?.valueOf(),u.end?.valueOf()].filter((e=>!!e));n.timeExtent.start=e.length?new Date(Math.max(...e)):void 0,n.timeExtent.end=t.length?new Date(Math.min(...t)):void 0}else n.timeExtent=u?.clone()}