/* eslint-disable no-console */
const path = require('path');
const fs = require('fs');
const http = require('http');
const serveStatic = require('serve-static');
const { URL } = require('url');

const filesPath = path.join(__dirname, './static');
const serve = serveStatic(filesPath, {
  index: ['index.html', 'index.htm'],
});

const server = http.createServer((req, res) => {
  try {
    const url = new URL(req.url, `http:${req.headers.host}`);
    if (url.pathname === '/dashboard') {
      req.url = `/${url.search}`;
    }
  } catch (error) {
    console.error(error);
  }

  return serve(req, res, () => {
    res.write(fs.readFileSync(path.join(filesPath, 'index.html')).toString());
    res.end();
  });
});

server.listen(process.env.BLOCKLET_PORT, () => {
  console.log(`block-explorer started on port http://127.0.0.1:${process.env.BLOCKLET_PORT}`);
});
