import * as vscode from "vscode";

export class WebviewSwitcherProvider implements vscode.WebviewViewProvider {
  private current: vscode.WebviewViewProvider;
  private view?: vscode.WebviewView;
  private context?: vscode.WebviewViewResolveContext;

  constructor(initial: vscode.WebviewViewProvider) {
    this.current = initial;
  }

  switchTo(provider: vscode.WebviewViewProvider) {
    this.current = provider;
    if (this.view) {
      this.current.resolveWebviewView(
        this.view,
        this.context!,
        new vscode.CancellationTokenSource().token,
      );
    }
  }

  resolveWebviewView(
    view: vscode.WebviewView,
    context: vscode.WebviewViewResolveContext,
    token: vscode.CancellationToken,
  ) {
    this.view = view;
    this.context = context;
    if (!this.current) {
      throw new Error("No provider set for WebviewSwitcherProvider");
    }
    this.current.resolveWebviewView(view, context, token);
  }
}
