import express, { Router } from 'express';
import { Application } from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';

type Routes = { path: string; router: Router }[];

class App {
  public app: Application;
  public port: number;

  constructor(opts: { port?: number; routes: Routes }) {
    this.app = express();
    this.port = opts.port || 3000;
    // @ts-ignore
    this.app.options('*', cors());
    // @ts-ignore
    this.app.use(
      cors({
        credentials: true,
        methods: 'GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE'
      })
    );
    this.app.use(bodyParser.urlencoded({ extended: false }));
    this.app.use(bodyParser.json());
    this.routes(opts.routes);
  }

  private routes(routes: Routes) {
    routes.map(route => {
      this.app.use(route.path, route.router);
    });
  }

  public listen() {
    this.app.listen(this.port, () => {
      console.log(`App listening on the http://localhost:${this.port}`);
    });
  }
}

export { App };
