import { constants, fsPath, log, express } from './common';

/**
 * Express middleware for serving the editor resources.
 */
export const editorServer = () => {
  log.info.gray(`Initializing ${log.magenta('editor.code')} routes:\n`);
  const router = express.router();

  const route = (url: string, dir: string) => {
    log.info.gray(` - route: ${log.cyan(url)}`);
    log.info.gray(` - dir:   ${log.cyan(dir)}`);
    log.info();

    /**
     * GET: Return the monaco editor dynamically loaded resources.
     */
    router.get(url, (req, res) => {
      const path = req.params[0];

      if (path.indexOf('..') > -1) {
        // Don't allow any parent system files to be served.
        return res.status(404).send('Not Found');
      }

      // Send the "Monaco Editor" resource.
      const file = fsPath.join(dir, path);
      if (constants.IS_DEV) {
        log.info(log.magenta('GET'), log.cyan(req.url));
        log.info.gray(`    ${file}`);
        log.info();
      }

      // Finish up.
      return res.sendFile(file);
    });
  };

  route(`${constants.URL.BASE}/*`, constants.EDITOR_RESOURCES.LOCAL);
  route(`/vs/*`, constants.VS.SOURCE);

  return router;
};
