const express = require('express')
const bodyParser = require('body-parser');
const request = require('request');

const app = express()
const port = 3000;

// Get the mongodb url
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/pred_records";

app.set('view engine', 'ejs')

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());


app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})


app.get('/', (req, res) => {
    res.render('index', {predictions:null})
})

app.post('/predict', (req,res) => {
    request.post({url:'http://127.0.0.1:5000/predict',formData:{
        text:req.body.plot
    }}, function (error, response, body) {
        console.error('error:', error); // Print the error
        console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
        console.log('body:', body); // Print the data received
        console.log(JSON.parse(body))
        console.log(JSON.parse(body).predictionText)
        // res.send(JSON.parse(JSON.parse(body).prediction)); //Display the response on the website

            //Add to db
        // Connect to the db
        MongoClient.connect(url, function(err, db) {
          if (err) throw err;
          db.collection('Predictions').insertOne({
            Plot: req.body.plot,
            Prediction: JSON.parse(body).predictionText
          })
        });

        res.render('predictions',{predictions:JSON.parse(JSON.parse(body).predictionText)})

        
      });      
    console.log(req.body.plot)
    // res.render('index', {});


});