/**
 * See:
 *    https://github.com/superRaytin/react-monaco-editor/blob/master/examples/nextjs/server.js
 */
import { constants, fs, fsPath, log, glob } from './common';

/**
 * Copies the monaco resources into the host module ready to be served.
 */
export async function copyResources() {
  const copy = async (options: { from: string; to: string }) => {
    const { from, to } = options;
    log.info.magenta(`Copy ${log.cyan('editor.code')} resources\n`);
    log.info.gray(` FROM: ${log.white(from)}`);
    log.info.gray(` TO:   ${log.white(to)}`);

    try {
      await fs.copy(from, to);
      return { success: true };
    } catch (error) {
      log.error(`Failed to copy resources from ${from}`);
      return { success: false, error };
    }
  };

  await copy({
    from: fsPath.join(constants.EDITOR_RESOURCES.SOURCE, 'external'),
    to: constants.EDITOR_RESOURCES.HOST,
  });
  log.info();
}

/**
 * Copies ECMA script defs loaded into the editor.
 */
export async function copyEcmascriptDefs() {
  const FROM_DIR = constants.ECMASCRIPT_DEFS.SOURCE;
  const TO_DIR = constants.ECMASCRIPT_DEFS.LOCAL;
  const paths = await glob.find(`${FROM_DIR}/*.d.ts`);

  log.info.magenta(
    `Copy ${log.cyan('ECMAScript')} language defs (".d.ts" files)\n`,
  );
  log.info.gray(` FROM: ${log.white(FROM_DIR)}`);
  log.info.gray(` TO:   ${log.white(TO_DIR)}`);

  for (const from of paths) {
    const filename = fsPath.basename(from);
    const to = fsPath.join(TO_DIR, filename);
    await fs.copy(from, to);
  }
  log.info();
}
