const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const txns = require('./models/txns');

// express app
const app = express();
// app.use(express.static(__dirname + '/public'));
app.listen(3000);

// connect to mongodb & listen for requests
const dbURI = "mongodb+srv://redkirti:Strong1234@cluster0.4oandf8.mongodb.net/orderbook?retryWrites=true&w=majority";

const connectionParams={
    useNewUrlParser: true,
    useUnifiedTopology: true 
}
mongoose.connect(dbURI,connectionParams)
    .then( () => {
        console.log('Connected to the database ')
    })
    .catch( (err) => {
        console.error(`Error connecting to the database. n${err}`);
    })
// register view engine
app.set('view engine', 'ejs');

// middleware & static files
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true}));
app.use(morgan('dev'));
app.use((req, res, next) => {
  res.locals.path = req.path;
  next();
});

app.post('/txns', (req, res) => {
    console.log(req.body);
    const txn = new txns(req.body);
    txn.save().then((result) => {
        res.send(result)
    })
    .catch((err) => {
        console.log(err);
    })
});

app.get('/txns', (req,res) => {
    txns.find().then((result) => {
        res.render('orderbook', {title: 'All Transactions', txns: result})
    })
    .catch((err) => {
        console.log(err);
    })
})

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

// 404 page
app.use((req, res) => {
  res.status(404).render('404', { title: '404' });
});