const http = require('http');
const url = require('url');
const fs = require('fs');
const puppeteer = require('./puppeteer');

// Create an HTTP server
const server = http.createServer((req, res) => {
  const parseUrl = url.parse(req.url, true);

  const fail = (error) => {
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.end(JSON.stringify({
      status: false,
      message: error
    }))
  }

  const config = {
    screenshotPath: './screenshot2.jpg'
  }

  if (parseUrl.query.url) {
    config.url = parseUrl.query.url
  }


  try {
    puppeteer(config)
      .then(function() {
        fs.readFile(config.screenshotPath, (err, data) => {
          if (err) {
            res.writeHead(500);
            res.end('Internal Server Error');
          } else {
            res.writeHead(200, {'Content-Type': 'image/jpeg'});
            res.end(data);
          }
        });
      })
      .catch(function(error) {
        fail(error.toString())
      });
  } catch (error) {
    fail(error.toString())
  }
});

// Set the port to listen to
const port = process.env.PORT || 4000;
const host = '0.0.0.0'; // Listen on all network interfaces

// Start the server
server.listen(port, host, () => {
  console.log(`Server running at http://${host}:${port}/`);
});
