import * as path from "path";
import { workspace, ExtensionContext } from "vscode";
import {
  LanguageClient,
  LanguageClientOptions,
  ServerOptions,
} from "vscode-languageclient/node";

let client: LanguageClient;

export function activate(context: ExtensionContext) {
  const config = workspace.getConfiguration("pit");
  const cellPath = config.get<string>("cellPath", "cell");
  const lspDir = path.join(context.extensionPath, "lsp");

  const serverOptions: ServerOptions = {
    command: cellPath,
    args: ["lsp/lsp"],
    options: { cwd: lspDir },
  };

  const clientOptions: LanguageClientOptions = {
    documentSelector: [{ scheme: "file", language: "pit" }],
    synchronize: {
      fileEvents: workspace.createFileSystemWatcher("**/*.{ce,cm}"),
    },
  };

  client = new LanguageClient(
    "pitLanguageServer",
    "ƿit Language Server",
    serverOptions,
    clientOptions
  );

  client.start();
}

export function deactivate(): Thenable<void> | undefined {
  if (!client) {
    return undefined;
  }
  return client.stop();
}
