var express = require('express');
var app = express();
var multer = require('multer')
var cors = require('cors');
var bodyParser = require("body-parser");
const fs = require('fs');

var corsOptions = {
    "origin": "*",
    "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
    "preflightContinue": false,
    "optionsSuccessStatus": 204
}
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors(corsOptions));

var storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, '/var/www/html/FBS')
    },
    filename: function(req, file, cb) {
        cb(null, Date.now() + '-' + file.originalname)
    }
})


var upload = multer({ storage: storage }).single('file')

app.post('/upload', function(req, res, next) {

    upload(req, res, function(err) {
        if (err instanceof multer.MulterError) {
            return res.status(500).json(err)
        } else if (err) {
            return res.status(500).json(err)
        }
        return res.status(200).send(req.file)

    })

});

const converter = require('json-2-csv');

app.post('/csv', (req, res, next) => {
    const csv = req;
    userData = req.body;

    converter.json2csv(userData, (err, csv) => {
        if (err) {
            throw err;
        }
        writetoFile(csv);
        // print CSV string
        console.log(csv);
    });

    res.send("OK");
});

function writetoFile(csv) {
    fs.writeFile('/var/www/html/appexe/natnats/23/resources/database/user_record.csv', csv, err => {
        if (err) {
            console.error(err)
            return
        }
    })
}

app.listen(8000, function() {

    console.log('App running on port 8000');

});
