import*as Common from"../common/common.js";import{Events as ResourceTreeModelEvents,ResourceTreeModel}from"./ResourceTreeModel.js";import{TargetManager}from"./SDKModel.js";let frameManagerInstance=null;export class FrameManager extends Common.ObjectWrapper.ObjectWrapper{constructor(){super(),this._eventListeners=new WeakMap,TargetManager.instance().observeModels(ResourceTreeModel,this),this._frames=new Map,this._framesForTarget=new Map,this._topFrame=null}static instance({forceNew:e}={forceNew:!1}){return frameManagerInstance&&!e||(frameManagerInstance=new FrameManager),frameManagerInstance}modelAdded(e){const t=e.addEventListener(ResourceTreeModelEvents.FrameAdded,this._frameAdded,this),r=e.addEventListener(ResourceTreeModelEvents.FrameDetached,this._frameDetached,this),a=e.addEventListener(ResourceTreeModelEvents.FrameNavigated,this._frameNavigated,this),s=e.addEventListener(ResourceTreeModelEvents.ResourceAdded,this._resourceAdded,this);this._eventListeners.set(e,[t,r,a,s]),this._framesForTarget.set(e.target().id(),new Set)}modelRemoved(e){const t=this._eventListeners.get(e);t&&Common.EventTarget.EventTarget.removeEventListeners(t);const r=this._framesForTarget.get(e.target().id());if(r)for(const a of r)this._decreaseOrRemoveFrame(a);this._framesForTarget.delete(e.target().id())}_frameAdded(e){const t=e.data,r=this._frames.get(t.id);r?this._frames.set(t.id,{frame:t,count:r.count+1}):this._frames.set(t.id,{frame:t,count:1}),this._resetTopFrame();const a=this._framesForTarget.get(t.resourceTreeModel().target().id());a&&a.add(t.id),this.dispatchEventToListeners(Events.FrameAddedToTarget,{frame:t})}_frameDetached(e){const t=e.data;this._decreaseOrRemoveFrame(t.id);const r=this._framesForTarget.get(t.resourceTreeModel().target().id());r&&r.delete(t.id)}_frameNavigated(e){const t=e.data;this.dispatchEventToListeners(Events.FrameNavigated,{frame:t}),t.isTopFrame()&&this.dispatchEventToListeners(Events.TopFrameNavigated,{frame:t})}_resourceAdded(e){const t=e.data;this.dispatchEventToListeners(Events.ResourceAdded,{resource:t})}_decreaseOrRemoveFrame(e){const t=this._frames.get(e);t&&(1===t.count?(this._frames.delete(e),this._resetTopFrame(),this.dispatchEventToListeners(Events.FrameRemoved,{frameId:e})):t.count--)}_resetTopFrame(){const e=this.getAllFrames().filter((e=>e.isTopFrame()));this._topFrame=e.length>0?e[0]:null}getFrame(e){const t=this._frames.get(e);return t?t.frame:null}getAllFrames(){return Array.from(this._frames.values(),(e=>e.frame))}getTopFrame(){return this._topFrame}}export const Events={FrameAddedToTarget:Symbol("FrameAddedToTarget"),FrameNavigated:Symbol("FrameNavigated"),FrameRemoved:Symbol("FrameRemoved"),ResourceAdded:Symbol("ResourceAdded"),TopFrameNavigated:Symbol("TopFrameNavigated")};