const express = require('express')
const app = express()
const config = require('config')    // https://github.com/lorenwest/node-config

const http =  require('http')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')

var Animal = require('../share/entities/Animal')


app.set('port', process.env.PORT || 3000)


app.get('/', (req, res) => res.send('Hello world!'))

app.get('/animals/', function (req, res) {
  var options = {
    hostname: config.get('service.001.host'),
    port: config.get('service.001.port'),
    path: '/animals/',
    method: 'GET',
    headers: { 'Content-Type': 'application/json' }
  };
  
  var req = http.request(options, function(res_) {
    res_.setEncoding('utf8');
    res_.on('data', function (data) {
      const json = JSON.parse(data);
      const token = json.token;
      
      if (!token) return res.status(500).json({ message: 'No token provided.' });

      jwt.verify(token, config.get('secret'), function(err, decoded) {
        if (err) return res.status(500).send({ message: 'Error decoding token.' });

        for(let item of decoded) {
          var pet = new Animal(item)
          console.log('Hello ' + pet.name)
        }
        
        res.status(200).json(decoded);
      });
    });
  });
  
  req.on('error', function(e) {
    console.error('Problem with request: ' + e.message)
    res.status(500).send("ERROR")
  });
  
  req.end();
});

app.listen(app.get('port'), () => console.log('Service listening on port '+app.get('port')+'!'))