'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const request = require('request-promise');
const log = require('./logger');
const app = express();
const apiMonkey = require('api-monkey');
const port = process.env.PORT || process.env.port || 3002;

const nodeEnv = process.env.NODE_ENV;
const eventApiUrl = nodeEnv === 'production' ? 'event_api' : 'http://localhost:3000/event';
const jobApiUrl = nodeEnv === 'production' ? 'job_api' : 'http://localhost:3001/job';

module.exports = app;

app.use(apiMonkey());

// For parsing application/json
app.use(bodyParser.json());
// For parsing application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

/**
 * REST Endpoint for creating an Event
 */
app.post('/events', (req, res) => {
  if (req.body) {
    request
      .post({ uri: eventApiUrl, json: req.body })
      .then(event => {
        log.debug('Created Event', event._id);
        return request.post({ uri: jobApiUrl, json: { eventId: event._id, publishingDate: req.body.publishingDate } })
      })
      .then(job => {
        log.debug('Created Job', job);
        return request.put({ uri: `${eventApiUrl}/${job.eventId}`, json: { jobId: job.id } })
      })
      .then(event => {
        log.debug('Updated Event', event);
        res.json(event);
      })
      .catch(err => {
        log.error(err);
        res.status(err.status || 500).json(err);
      });
  }
});

/**
 * REST Endpoint for reading an Event
 */
app.get('/events/:id', (req, res) => {
  const eventId = req.params.id;
  if (eventId) {
    request.get({ uri: `${eventApiUrl}/${eventId}` })
      .then(event => {
        log.debug('Read Event', event);
        res.json(JSON.parse(event));
      })
      .catch(err => {
        log.error(err);
        res.status(err.status || 500).json(err);
      });
  } else {
    var err = new Error('id is not defined');
    res.status(400).json(err);
  }
});

/**
 * REST Endpoint for updating an Event
 */
app.put('/events/:id', (req, res) => {
  const eventId = req.params.id;
  if (eventId && req.body) {
    request
      .put({ uri: `${eventApiUrl}/${eventId}`, json: req.body })
      .then(event => {
        if (req.body.publishingDate) {
          return request
            .put({ uri: `${jobApiUrl}/${event.jobId}`, json: { publishingDate: req.body.publishingDate } })
            .then(job => event);
        } else {
          return Promise.resolve(event);
        }
      })
      .then(event => res.json(event))
      .catch(err => {
        log.error(err);
        res.status(err.status || 500).json(err);
      });
  } else {
    const err = new Error('id is not defined');
    res.status(400).json(err);
  }
});

/**
 * REST Endpoint for deleting an Event
 */
app.delete('/events/:id', (req, res) => {
  const eventId = req.params.id;
  if (eventId !== undefined) {
    request
      .del({ uri: `${eventApiUrl}/${eventId}` })
      .then(event => {
        log.info('Deleted Event', event);
        return request.del({ uri: `${jobApiUrl}/${JSON.parse(event).jobId}` })
      })
      .then(() => {
        log.info('Deleted Job for Event', eventId);
        res.status(200).end();
      })
      .catch(err => {
        log.error(err);
        res.status(err.status || 500).json(err);
      });
  } else {
    var err = new Error('id is not defined');
    res.status(400).json(err);
  }
});

app.listen(port);
log.info(`Wrapper API listening at ${port}`)

@@ -825,23 +825,16 @@
  request
-%0A      
 .post(%7B 
@@ -857,32 +857,60 @@
 , json: req.body
+, headers: req.monkeyHeaders
  %7D)%0A      .then(
@@ -985,31 +985,54 @@
 turn request
-.post(%7B
+%0A          .post(%7B%0A           
  uri: jobApi
@@ -1031,24 +1031,36 @@
 : jobApiUrl,
+%0A           
  json: %7B eve
@@ -1113,27 +1113,78 @@
 ishingDate %7D
+,%0A            headers: req.monkeyHeaders%0A         
  %7D)
+;
 %0A      %7D)%0A  
@@ -1263,22 +1263,45 @@
  request
-.put(%7B
+%0A          .put(%7B%0A           
  uri: %60$
@@ -1326,24 +1326,36 @@
 b.eventId%7D%60,
+%0A           
  json: %7B job
@@ -1366,16 +1366,66 @@
 job.id %7D
+,%0A            headers: req.monkeyHeaders%0A         
  %7D)%0A    
@@ -1820,32 +1820,60 @@
 Url%7D/$%7BeventId%7D%60
+, headers: req.monkeyHeaders
  %7D)%0A      .then(
@@ -2392,16 +2392,44 @@
 req.body
+, headers: req.monkeyHeaders
  %7D)%0A    
@@ -2521,32 +2521,46 @@
           .put(%7B
+%0A             
  uri: %60$%7BjobApiU
@@ -2575,24 +2575,38 @@
 ent.jobId%7D%60,
+%0A             
  json: %7B pub
@@ -2643,16 +2643,70 @@
 ngDate %7D
+,%0A              headers: req.monkeyHeaders%0A           
  %7D)%0A    
@@ -3294,36 +3294,37 @@
 %3E %7B%0A        log.
-info
+debug
 ('Deleted Event'
@@ -3355,22 +3355,45 @@
  request
-.del(%7B
+%0A          .del(%7B%0A           
  uri: %60$
@@ -3427,27 +3427,78 @@
 ent).jobId%7D%60
+,%0A            headers: req.monkeyHeaders%0A         
  %7D)
+;
 %0A      %7D)%0A  
@@ -3527,20 +3527,21 @@
     log.
-info
+debug
 ('Delete

Add & integrate api-monkey