import*as Common from'../common/common.js';import{DebuggerModel,Location}from'./DebuggerModel.js';import{RuntimeModel}from'./RuntimeModel.js';import{Capability,SDKModel,Target}from'./SDKModel.js';export class CPUProfilerModel extends SDKModel{constructor(target){super(target);this._isRecording=false;this._nextAnonymousConsoleProfileNumber=1;this._anonymousConsoleProfileIdToTitle=new Map();this._profilerAgent=target.profilerAgent();this._preciseCoverageDeltaUpdateCallback=null;target.registerProfilerDispatcher(this);this._profilerAgent.enable();this._debuggerModel=(target.model(DebuggerModel));}
runtimeModel(){return this._debuggerModel.runtimeModel();}
debuggerModel(){return this._debuggerModel;}
consoleProfileStarted(id,scriptLocation,title){if(!title){title=Common.UIString.UIString('Profile %d',this._nextAnonymousConsoleProfileNumber++);this._anonymousConsoleProfileIdToTitle.set(id,title);}
this._dispatchProfileEvent(Events.ConsoleProfileStarted,id,scriptLocation,title);}
consoleProfileFinished(id,scriptLocation,cpuProfile,title){if(!title){title=this._anonymousConsoleProfileIdToTitle.get(id);this._anonymousConsoleProfileIdToTitle.delete(id);}
self.runtime.loadModulePromise('profiler').then(()=>{this._dispatchProfileEvent(Events.ConsoleProfileFinished,id,scriptLocation,title,cpuProfile);});}
_dispatchProfileEvent(eventName,id,scriptLocation,title,cpuProfile){const debuggerLocation=Location.fromPayload(this._debuggerModel,scriptLocation);const globalId=this.target().id()+'.'+id;const data=({id:globalId,scriptLocation:debuggerLocation,cpuProfile:cpuProfile,title:title,cpuProfilerModel:this});this.dispatchEventToListeners(eventName,data);}
isRecordingProfile(){return this._isRecording;}
startRecording(){this._isRecording=true;const intervalUs=self.Common.settings.moduleSetting('highResolutionCpuProfiling').get()?100:1000;this._profilerAgent.setSamplingInterval(intervalUs);return this._profilerAgent.start();}
stopRecording(){this._isRecording=false;return this._profilerAgent.stop();}
startPreciseCoverage(jsCoveragePerBlock,preciseCoverageDeltaUpdateCallback){const callCount=false;this._preciseCoverageDeltaUpdateCallback=preciseCoverageDeltaUpdateCallback;return this._profilerAgent.startPreciseCoverage(callCount,jsCoveragePerBlock);}
async takePreciseCoverage(){const r=await this._profilerAgent.invoke_takePreciseCoverage({});const timestamp=(r&&r.timestamp)||0;const coverage=(r&&r.result)||[];return{timestamp,coverage};}
stopPreciseCoverage(){this._preciseCoverageDeltaUpdateCallback=null;return this._profilerAgent.stopPreciseCoverage();}
preciseCoverageDeltaUpdate(timestampInSeconds,occassion,coverageData){if(this._preciseCoverageDeltaUpdateCallback){this._preciseCoverageDeltaUpdateCallback(timestampInSeconds,occassion,coverageData);}}}
export const Events={ConsoleProfileStarted:Symbol('ConsoleProfileStarted'),ConsoleProfileFinished:Symbol('ConsoleProfileFinished')};SDKModel.register(CPUProfilerModel,Capability.JS,true);