import*as Common from"../common/common.js";import*as Platform from"../platform/platform.js";import{formatterWorkerPool}from"./FormatterWorkerPool.js";export class FormatterInterface{}FormatterInterface.format=function(t,o,i,r){t.isDocumentOrScriptOrStyleSheet()?new ScriptFormatter(o,i,r):new ScriptIdentityFormatter(o,i,r)},FormatterInterface.locationToPosition=function(t,o,i){return(o?t[o-1]+1:0)+i},FormatterInterface.positionToLocation=function(t,o){const i=Platform.ArrayUtilities.upperBound(t,o-1,Platform.ArrayUtilities.DEFAULT_COMPARATOR);let r;return r=i?o-t[i-1]-1:o,[i,r]};export class ScriptFormatter{constructor(t,o,i){this._mimeType=t,this._originalContent=o.replace(/\r\n?|[\n\u2028\u2029]/g,"\n").replace(/^\uFEFF/,""),this._callback=i,this._initialize()}async _initialize(){const t=formatterWorkerPool(),o=Common.Settings.Settings.instance().moduleSetting("textEditorIndent").get(),i=await t.format(this._mimeType,this._originalContent,o);i?this._didFormatContent(i):this._callback(this._originalContent,new IdentityFormatterSourceMapping)}_didFormatContent(t){const o=Platform.StringUtilities.findLineEndingIndexes(this._originalContent),i=Platform.StringUtilities.findLineEndingIndexes(t.content),r=new FormatterSourceMappingImpl(o,i,t.mapping);this._callback(t.content,r)}}class ScriptIdentityFormatter{constructor(t,o,i){i(o,new IdentityFormatterSourceMapping)}}export class FormatterSourceMapping{originalToFormatted(t,o){throw new Error("Not implemented yet.")}formattedToOriginal(t,o){throw new Error("Not implemented yet.")}}class IdentityFormatterSourceMapping{originalToFormatted(t,o){return[t,o||0]}formattedToOriginal(t,o){return[t,o||0]}}class FormatterSourceMappingImpl{constructor(t,o,i){this._originalLineEndings=t,this._formattedLineEndings=o,this._mapping=i}originalToFormatted(t,o){const i=FormatterInterface.locationToPosition(this._originalLineEndings,t,o||0),r=this._convertPosition(this._mapping.original,this._mapping.formatted,i||0);return FormatterInterface.positionToLocation(this._formattedLineEndings,r)}formattedToOriginal(t,o){const i=FormatterInterface.locationToPosition(this._formattedLineEndings,t,o||0),r=this._convertPosition(this._mapping.formatted,this._mapping.original,i);return FormatterInterface.positionToLocation(this._originalLineEndings,r||0)}_convertPosition(t,o,i){const r=Platform.ArrayUtilities.upperBound(t,i,Platform.ArrayUtilities.DEFAULT_COMPARATOR)-1;let n=o[r]+i-t[r];return r<o.length-1&&n>o[r+1]&&(n=o[r+1]),n}}