import{SearchOptions,SearchResults,EnrichedSearchResults,IntermediateSearchResults}from"../type.js";import{create_object,is_object,sort_by_length_down}from"../common.js";import Index from"../index.js";import default_compress from"../compress.js";import Resolver from"../resolver.js";import{intersect}from"../intersect.js";import resolve_default from"../resolve/default.js";Index.prototype.search=function(a,b,c){if(c||(b||"object"!=typeof a?"object"==typeof b&&(c=b,b=0):(c=a,a="")),c&&c.cache){c.cache=!1;const d=this.searchCache(a,b,c);return c.cache=!0,d}let d,e,f,g,h,i,j,k,l=[],m=0;c&&(a=c.query||a,b=c.limit||b,m=c.offset||0,e=c.context,f=c.suggest,g=c.resolve,k=g&&c.enrich,i=c.boost,j=c.resolution,h=this.db&&c.tag),"undefined"==typeof g&&(g=this.resolve),e=this.depth&&!1!==e;let n=this.encoder.encode(a,!e);if(d=n.length,b=b||(g?100:0),1===d)return single_term_query.call(this,n[0],"",b,m,g,k,h);if(2===d&&e&&!f)return single_term_query.call(this,n[1],n[0],b,m,g,k,h);let o,p=create_object(),q=0;if(e&&(o=n[0],q=1),j||0===j||(j=o?this.resolution_ctx:this.resolution),this.db){if(this.db.search){const a=this.db.search(this,n,b,m,f,g,k,h);if(!1!==a)return a}const a=this;return async function(){for(let b,c;q<d;q++){if(c=n[q],c&&!p[c]){if(p[c]=1,b=await a._get_array(c,o,0,0,!1,!1),b=add_result(b,l,f,j),b){l=b;break}!o||f&&b&&l.length||(o=c)}f&&o&&q==d-1&&!l.length&&(j=a.resolution,o="",q=-1,p=create_object())}return return_result(l,j,b,m,f,i,g)}()}for(let e,g;q<d;q++){if(g=n[q],g&&!p[g]){if(p[g]=1,e=this._get_array(g,o,0,0,!1,!1),e=add_result(e,l,f,j),e){l=e;break}!o||f&&e&&l.length||(o=g)}f&&o&&q==d-1&&!l.length&&(j=this.resolution,o="",q=-1,p=create_object())}return return_result(l,j,b,m,f,i,g)};function return_result(a,b,c,d,e,f,g){let h=a.length,i=a;if(1<h)i=intersect(a,b,c,d,e,f,g);else if(1===h)return g?resolve_default.call(null,a[0],c,d):new Resolver(a[0],this);return g?i:new Resolver(i,this)}function single_term_query(a,b,c,d,e,f,g){const h=this._get_array(a,b,c,d,e,f,g);return this.db?h.then(function(a){return e?a||[]:new Resolver(a,this)}):h&&h.length?e?resolve_default.call(this,h,c,d):new Resolver(h,this):e?[]:new Resolver([],this)}function add_result(a,b,c,d){let e=[];if(a&&a.length){if(a.length<=d)return void b.push(a);for(let b,c=0;c<d;c++)(b=a[c])&&(e[c]=b);if(e.length)return void b.push(e)}return c?void 0:e}Index.prototype._get_array=function(a,b,c,d,e,f,g){let h,i;return(b&&(i=this.bidirectional&&a>b,i&&(i=b,b=a,a=i)),this.compress&&(a=default_compress(a),b&&(b=default_compress(b))),this.db)?this.db.get(a,b,c,d,e,f,g):(b?(h=this.ctx.get(b),h=h&&h.get(a)):h=this.map.get(a),h)};