import { Selection, ProjectState, CommandSettings } from '../../types';
import runInSandbox from './runInSandbox';

const runCommand = (commandTypescriptCode: string, receiveDiscoveredSettings?: (discoveredSettings: CommandSettings<any>) => void) => {
  return async <T>(projectState: ProjectState, selection: Selection, settings: T, isTest: boolean = false): Promise<[ProjectState, Selection]> => {
    const ts = await import('typescript');
    const transpiled = ts.transpile(commandTypescriptCode.replace(/import.*/g, ''));

    const [newProjectState, newSelection, discoveredSettings] = await runInSandbox(
      transpiled,
      projectState,
      selection,
      settings,
      isTest
    );
    if (receiveDiscoveredSettings) {
      receiveDiscoveredSettings(discoveredSettings);
    }
    return [newProjectState, newSelection] as [ProjectState, Selection];
  }
}

export default runCommand;
