import * as vscode from "vscode";
import { SIDEBAR_BUNDLE_DIR } from "../constants";

export const getStaticMeta = (
  webview: vscode.Webview,
  extensionUri: vscode.Uri,
  nonce: string,
): string => {
  return `
        <meta
          http-equiv="Content-Security-Policy"
          content="
            default-src 'none';
            script-src 'unsafe-eval' ${webview.cspSource} https://* https://*.posthog.com https://us-assets.i.posthog.com 'nonce-${nonce}';
			      connect-src ${webview.cspSource} https://* https://*.posthog.com;
            style-src ${webview.cspSource} 'unsafe-inline';
            font-src ${webview.cspSource};
            img-src ${webview.cspSource} https:;
          "
        />
        ${getStyleHeadTags(webview, extensionUri)}
  `;
};

export const getStyleHeadTags = (
  webview: vscode.Webview,
  extensionUri: vscode.Uri,
): string => {
  const stylesUri = webview.asWebviewUri(
    vscode.Uri.joinPath(
      extensionUri,
      SIDEBAR_BUNDLE_DIR,
      "assets",
      "index.css",
    ),
  );

  const codiconFontUri = webview.asWebviewUri(
    vscode.Uri.joinPath(
      extensionUri,
      SIDEBAR_BUNDLE_DIR,
      "assets",
      "codicon.ttf",
    ),
  );
  return `<style>
          @font-face{font-family:codicon;font-display:block;src:url(${codiconFontUri}) format("truetype")}
        </style>
        <link rel="stylesheet" type="text/css" href="${stylesUri}" />`;
};

export const getScriptTag = (
  webview: vscode.Webview,
  extensionUri: vscode.Uri,
  nonce: string,
): string => {
  const scriptUri = webview.asWebviewUri(
    vscode.Uri.joinPath(extensionUri, SIDEBAR_BUNDLE_DIR, "assets", "index.js"),
  );
  return `<script nonce="${nonce}" src="${scriptUri}"></script>`;
};

export const generateNonce = (): string => {
  return Array.from({ length: 32 }, () =>
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(
      Math.floor(Math.random() * 62),
    ),
  ).join("");
};
