import express from 'express';
import http from 'http';
import compression from 'compression';
import helmet from 'helmet';
import multer from 'multer';
import bodyParser from 'body-parser';
import Hack from '../components/Hack';
import PlateRecognizr from '../api/PlateRecognizr';

const PORT = process.env.PORT || '8000';
const upload = multer({ dest: '/tmp' });

class BasicApi {
  app;
  server;
  hack;
  alpr;

  constructor() {
    this.app = express();
    this.app.use(express.static('public'));
    this.app.use(bodyParser.urlencoded({ extended: false }));
    this.app.use(compression());
    this.app.use(helmet());
    this.app.use((req, res, next) => {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
      next();
    });
    this.server = http.createServer(this.app);
    this.hack = new Hack();
    this.alpr = new PlateRecognizr();
  }

  init() {
    this.server.listen(PORT, () => {
      console.log(`Server running at port ${PORT}`);
    });
    this.registerEndpoints();
  }

  registerEndpoints() {
    this.app.get('/:plate', async ({ params }, response) => {
      const { plate } = params;
      await this.hack.init(plate);
      response
        .status(200)
        .send(this.hack.getCar());
    });

    this.app.post('/alpr', upload.single('upload'), async ({ body }, response) => {
      const { upload: image } = body;
      console.log(Object.keys(body));
      const plate = await (await this.alpr.fetch(image)).json();
      console.log(plate);
      response.status(200).json(plate);
    });
  }
}

export default BasicApi;
