#!/bin/sh
':' //; exec "$(command -v nodejs || command -v node)" "$0" "$@"

import express, {Request, Response, NextFunction} from 'express';
import path from 'path';
import cors from 'cors';
import http from 'http';
import morgan from 'morgan';
// import bodyParser from 'body-parser'
import 'dotenv/config';

import cliRouter from './routers/cli';
import homeRouter from './routers/home';
import pluginsRouter from './routers/plugins';
import navsRouter from './routers/navigators';
import {createSocketServer} from './websocket';
import {ensureDefaultWorkspace} from './controllers/workspace';

const app = express();
app.use(morgan(':method :url :status'));
app.set('view engine', 'pug');
const server = http.createServer(app);
app.use(cors());
// export const jsonParser = bodyParser.json({limit: '50mb'});
createSocketServer(server);

app.use(`/plugin-server/cli`, cliRouter);
app.use(`/plugin-server/home`, homeRouter);
app.use(`/plugin-server/plugins`, pluginsRouter);
app.use(`/plugin-server/navigators`, navsRouter);

// const staticOptions = {
//   maxAge: '1000d', 
//   etag: true,   
//   lastModified: true, 
//   immutable: true 
// };
app.use('/plugin-server/public', express.static(path.resolve(__dirname, 'public')));//, staticOptions));
// For handling spa
app.use('/plugin-server/public/ui/*', (req, res) => {
  res.sendFile(path.resolve(__dirname, 'public/ui/index.html'));
});

app.get('/plugin-server/healthcheck', (req, res) => {
  res.send('ok');
});

app.use((err: any, req: Request, res: Response, next: NextFunction) => {
  if (res.headersSent) {
    return next(err)
  }
  res.status(500)
  console.error("GLOBAL_ERROR", err);
  res.end();
});

ensureDefaultWorkspace().then(startupMessage => {
  server.listen(3100, () => {
    console.log(`visit http://localhost:3100/plugin-server/cli/workspaces/list`);
    console.log(startupMessage);
  });
});

