import * as vscode from 'vscode';

export function handleClipboardAndOpen(msg: any): boolean {
  if (msg?.type === 'copy' && typeof msg.text === 'string') {
    vscode.env.clipboard.writeText(msg.text);
    vscode.window.showInformationMessage('Copied to clipboard.');
    return true;
  }
  if (msg?.type === 'open' && typeof msg.text === 'string') {
    vscode.env.openExternal(vscode.Uri.parse(msg.text));
    return true;
  }
  return false;
}

export function singletonPanel(
  store: { panel: vscode.WebviewPanel | null },
  viewType: string,
  title: string
): { panel: vscode.WebviewPanel; isNew: boolean } {
  if (store.panel) {
    store.panel.reveal();
    return { panel: store.panel, isNew: false };
  }
  const panel = vscode.window.createWebviewPanel(
    viewType,
    title,
    vscode.ViewColumn.Active,
    { enableScripts: true, retainContextWhenHidden: true }
  );
  store.panel = panel;
  panel.onDidDispose(() => { store.panel = null; });
  return { panel, isNew: true };
}
