import{create_object}from"../common.js";import Index,{autoCommit}from"../index.js";import default_compress from"../compress.js";import{KeystoreArray,KeystoreMap}from"../keystore.js";Index.prototype.add=function(a,b,c,d){if(b&&(a||0===a)){if(!d&&!c&&this.reg.has(a))return this.update(a,b);const e=this.depth;b=this.encoder.encode(b,!e);const f=b.length;if(f){const d=create_object(),g=create_object(),h=this.resolution;for(let j=0;j<f;j++){let i=b[this.rtl?f-1-j:j],k=i.length;if(k&&(e||!g[i])){let l=this.score?this.score(b,i,j,null,0):get_score(h,f,j),m="";switch(this.tokenize){case"tolerant":if(this._push_index(g,i,l,a,c),2<k){for(let b,d,e,f,h=1;h<k-1;h++)b=i.charAt(h),d=i.charAt(h+1),e=i.substring(0,h)+d,f=i.substring(h+2),m=e+b+f,this._push_index(g,m,l,a,c),m=e+f,this._push_index(g,m,l,a,c);this._push_index(g,i.substring(0,i.length-1),l,a,c)}break;case"full":if(2<k){for(let d,e=0;e<k;e++)for(let l=k;l>e;l--){m=i.substring(e,l),d=this.rtl?k-1-e:e;const n=this.score?this.score(b,i,j,m,d):get_score(h,f,j,k,d);this._push_index(g,m,n,a,c)}break}case"bidirectional":case"reverse":if(1<k){for(let d=k-1;0<d;d--){m=i[this.rtl?k-1-d:d]+m;const e=this.score?this.score(b,i,j,m,d):get_score(h,f,j,k,d);this._push_index(g,m,e,a,c)}m=""}case"forward":if(1<k){for(let b=0;b<k;b++)m+=i[this.rtl?k-1-b:b],this._push_index(g,m,l,a,c);break}default:if(this._push_index(g,i,l,a,c),e&&1<f&&j<f-1){const g=this.resolution_ctx,h=i,k=Math.min(e+1,this.rtl?j+1:f-j);for(let e=1;e<k;e++){i=b[this.rtl?f-1-j-e:j+e];const l=this.bidirectional&&i>h,m=this.score?this.score(b,h,j,i,e-1):get_score(g+(f/2>g?0:1),f,j,k-1,e-1);this._push_index(d,l?h:i,m,a,c,l?i:h)}}}}}this.fastupdate||this.reg.add(a)}}return this.db&&(this.commit_task.push(c?{ins:a}:{del:a}),this.commit_auto&&autoCommit(this)),this},Index.prototype._push_index=function(a,b,c,d,e,f){let g,h;if(!(g=a[b])||f&&!g[f]){if(f?(a=g||(a[b]=create_object()),a[f]=1,this.compress&&(f=default_compress(f)),h=this.ctx,g=h.get(f),g?h=g:h.set(f,h=this.keystore?new KeystoreMap(this.keystore):new Map)):(h=this.map,a[b]=1),this.compress&&(b=default_compress(b)),g=h.get(b),g?h=g:h.set(b,h=g=[]),e)for(let a,b=0;b<g.length;b++)if(a=g[b],a&&a.includes(d)){if(b<=c)return;if(a.splice(a.indexOf(d),1),this.fastupdate){const b=this.reg.get(d);b&&b.splice(b.indexOf(a),1)}break}if(h=h[c]||(h[c]=[]),h.push(d),2147483647===h.length){const a=new KeystoreArray(h);if(this.fastupdate)for(let b of this.reg.values())b.includes(h)&&(b[b.indexOf(h)]=a);g[c]=h=a}if(this.fastupdate){const a=this.reg.get(d);a?a.push(h):this.reg.set(d,[h])}}};function get_score(a,b,c,d,e){return c&&1<a?b+(d||0)<=a?c+(e||0):0|(a-1)/(b+(d||0))*(c+(e||0))+1:0}