/* COPYRIGHT Esri - https://js.arcgis.com/5.0.18/LICENSE.txt */
import has from"../../core/has.js";import{getOrCreateMapValue as e}from"../../core/MapUtils.js";import{parseWhereClause as t,sqlTimestampLiteral as r}from"../../core/sql.js";import{visitSqlNode as n}from"../../core/sql/sqlVisitor.js";import{isAgolSecuredProxyService as i,isHostedAgolService as o}from"./arcgisLayerUrl.js";import{collectSQLFieldNames as a}from"./fieldUtils.js";function s(e,t){if(!e||!has("featurelayer-relative-time-queries-enabled"))return 0;const r=i(e);return o(e)||r?(t??0)>0||r?has("featurelayer-relative-time-queries-bin-window-public")??1:has("featurelayer-relative-time-queries-bin-window-private")??60:0}function u(e){return(has("featurelayer-relative-time-queries-enabled")??!0)&&f(e)}function f(e){return null!=e&&/CURRENT_TIMESTAMP/gi.test(e)}const l=new WeakMap;async function c(e,r){if(!r||!f(r))return[];const n=await t(r,e);if(!n.isStandardized)return[];const i=y(n),o=new Set(i.map(e=>e.left.column));return Array.from(o)}async function p(e,t,r){(await c(t,r)).length>0&&await a(e,t,r)}async function m(e,r,n,i=Date.now()){if(!r||!n||!f(r))return r;const o=await t(r,e);if(!o.isStandardized)return r;const[a,s]=d(i,n),u=y(o).flatMap(e=>[{replacement:"BETWEEN"===e.operator?a:s,start:e.right.value[0].left.location.start.offset,end:e.right.value[0].left.location.end.offset},{replacement:"BETWEEN"===e.operator?s:a,start:e.right.value[1].location.start.offset,end:e.right.value[1].location.end.offset}]).sort((e,t)=>t.start-e.start);let l=r;for(const{replacement:t,start:f,end:c}of u)l=l.slice(0,f)+t+l.slice(c);return l}function y(t){return e(l,t,()=>E(t.parseTree))}function d(e,t){const n=60*t*1e3,i=e-e%n,o=i+n;return[r(new Date(i),"date"),r(new Date(o),"date")]}function E(e){const t=[],r={"binary-expression":e=>{"AND"===e.operator||"OR"===e.operator?(n(e.left,r),n(e.right,r)):w(e)&&t.push(e)}};return n(e,r),t}function w(e){return"binary-expression"===e.type&&("BETWEEN"===e.operator||"NOTBETWEEN"===e.operator)&&"column-reference"===e.left.type&&g(e.right)}function g(e){if("expression-list"!==e.type||2!==e.value.length)return!1;const[t,r]=e.value;return(h(t)||v(t))&&b(r)}function h(e){return"binary-expression"===e.type&&b(e.left)&&T(e.right)}function v(e){return"binary-expression"===e.type&&b(e.left)&&q(e.right)}function b(e){return"current-time"===e.type&&"timestamp"===e.mode}function T(e){return"interval"===e.type}function q(e){return"number"===e.type}export{u as canConvertSqlRelativeTime,p as collectRelativeTimeFields,c as getRelativeTimeFields,s as getRelativeTimeQueryBinWindowSize,f as hasSqlRelativeTime,m as sqlRelativeTimeToAbsolute};
