var express = require('express');
var session = require("express-session")
var bodyParser = require('body-parser')
var bcrypt   = require('bcrypt-nodejs');
/*
var mje = require('mongo-json-escape')
const mongo = require('mongodb').MongoClient
const mongoObjectID = require('mongodb').ObjectID
const url = 'mongodb://localhost:27017/'
*/
const fs = require('fs')
const fileExists = async path => !!(await fs.promises.stat(path).catch(e => false));


var rp = require('request-promise-native');

var textParser = bodyParser.text({limit: '50mb', extended: true})

var jsonParser = bodyParser.json({limit: '50mb', extended: true})
// configure app to use bodyParser()
// this will let us get the data from a POST
var router = express.Router();

router.use(bodyParser.raw({type: 'application/octet-stream', limit : '2mb'}))
router.use(bodyParser.text({ type: 'text/*' }))

router.post("/file", async (req,res,next) => {
    const filename = req.query.filename
    fs.writeFile(filename, req.body, (err) => {
        res.send("ok")
    })
})


router.get("/file", async (req,res,next) => {
    const filename = req.query.filename
    try {
        const result = await fileExists(filename)
        if (!result){
            res.status(500).send({
                error: 'file doesnt exist'
            })
            return;
        }
        res.sendFile(filename, { root: '.' })
    }
    catch (ex) {
        res.send({
            error: 'file doesnt exist'
        })
        return;
    }
})
module.exports = router;
