/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
import{ArcadeDate as n}from"../ArcadeDate.js";import{isEmpty as t}from"../containerUtils.js";import{ArcadeExecutionError as e}from"../executionError.js";import{B as r,m as a,j as i,n as o,J as s,L as u,K as c}from"../../chunks/languageUtils.js";import{calculateStat as f}from"./fieldStats.js";import{SqlTimeStampOffset as m}from"../../core/sql/SqlTimestampOffset.js";import d from"../../core/sql/WhereClause.js";import{DateTime as l}from"luxon";import{isArray as g,isString as y,isBoolean as p,isDate as A}from"../../support/guards.js";async function F(n,t,e,r){if(1===e.length){if(g(e[0]))return f(n,e[0],s(e[1],-1));if(i(e[0]))return f(n,e[0].toArray(),s(e[1],-1))}else if(2===e.length){if(g(e[0]))return f(n,e[0],s(e[1],-1));if(i(e[0]))return f(n,e[0].toArray(),s(e[1],-1));if(a(e[0])){const a=await e[0].load(),i=await w(d.create(e[1],{fieldsIndex:a.getFieldsIndex(),timeZone:a.dateFieldsTimeZoneDefaultUTC}),r,t);return h(t,await e[0].calculateStatistic(n,i,s(e[2],1e3),t.abortSignal))}}else if(3===e.length&&a(e[0])){const a=await e[0].load(),i=await w(d.create(e[1],{fieldsIndex:a.getFieldsIndex(),timeZone:a.dateFieldsTimeZoneDefaultUTC}),r,t);return h(t,await e[0].calculateStatistic(n,i,s(e[2],1e3),t.abortSignal))}return f(n,e,-1)}function h(t,e){return m.isTimestampOffset(e)?n.fromReaderAsTimeStampOffset(e.toStorageFormat()):A(e)?n.dateJSAndZoneToArcadeDate(e,c(t)):l.isDateTime(e)?n.dateTimeToArcadeDate(e):e}async function w(n,t,e){const r=n.getVariables();if(r.length>0){const a={};for(const n of r)a[n]=t.evaluateIdentifier(e,{name:n});n.parameters=a}return n}function S(n){"async"===n.mode&&(n.functions.stdev=function(t,e){return n.standardFunctionAsync(t,e,(e,r,a)=>F("stdev",t,a,n))},n.functions.variance=function(t,e){return n.standardFunctionAsync(t,e,(e,r,a)=>F("variance",t,a,n))},n.functions.average=function(t,e){return n.standardFunctionAsync(t,e,(e,r,a)=>F("mean",t,a,n))},n.functions.mean=function(t,e){return n.standardFunctionAsync(t,e,(e,r,a)=>F("mean",t,a,n))},n.functions.sum=function(t,e){return n.standardFunctionAsync(t,e,(e,r,a)=>F("sum",t,a,n))},n.functions.min=function(t,e){return n.standardFunctionAsync(t,e,(e,r,a)=>F("min",t,a,n))},n.functions.max=function(t,e){return n.standardFunctionAsync(t,e,(e,r,a)=>F("max",t,a,n))},n.functions.count=function(t,s){return n.standardFunctionAsync(t,s,async(n,u,c)=>{if(r(c,1,1,t,s),null==c[0])return 0;if(a(c[0]))return c[0].count(n.abortSignal);if(g(c[0])||y(c[0]))return c[0].length;if(i(c[0]))return c[0].length();if(o(c[0]))return c[0].entryCount();throw new e(t,"InvalidParameter",s)})},n.functions.isempty=function(i,o){return n.standardFunctionAsync(i,o,async(n,i,o)=>{if(r(o,1,2,n,i),o.length>=2&&!p(o[1]))throw new e(n,"InvalidParameter",i);return s(o[1],!1)?a(o[0])?await o[0].isEmpty(n.abortSignal):t(o[0]):u(o[0])})})}export{S as registerFunctions};
