import { MainApi } from '../common/mainApi';
import { OSInfo } from '../common/preloadApi';
import { RendererApi } from '../common/rendererApi';

export async function runAction(rapi: RendererApi, main: MainApi, os: OSInfo): Promise<boolean> {
  const dir = await main.makeTmpDirectory();
  const execFileName = os.isWindows ? 'hello.exe' : 'hello';

  const cppFile = `${dir}${os.separator}hello.cpp`;
  const execFile = `${dir}${os.separator}${execFileName}`;
  console.log(cppFile);
  const code = `
  #include <iostream>
  int main(int argc, char const *argv[])
  {
    std::cout << "Hello World" << std::endl;
    return 0;
  }
  `;

  if (!(await main.saveTextFile(cppFile, code))) {
    rapi.err('ファイルの保存に失敗');
    return false;
  }

  if (!(await main.compile(cppFile, execFile))) {
    rapi.err('コンパイルに失敗');
    return false;
  }

  if ((await main.exec(execFile)) != 0) {
    rapi.err('実行に失敗');
    return false;
  }

  return true;
}
