// Upload de file
const express = require( 'express' );
const fs = require( 'fs-extra' );
// Classes
const UploadFile = require( '../models/UploadFiles' );
const Outputs = require( '../models/Outputs' );
//const Outputstest = require('../models/Outputstest');
// Middlewares
const checkHeaders = require( '../middlewares/checkHeaders' );
const isAuthenticated = require( '../middlewares/isAuthenticated' );
const router = express.Router();


router.post( '/ggsheet2json', checkHeaders, async ( req, res ) => {
	logger.info( 'route outputs sheet to json' );
	let result = await Outputs.ggsheet2json( req.body, req.session.header );
	res.send( result );
} );




// checkHeaders, isuploadFileValid
router.post( '/msg', checkHeaders, async ( req, res ) => {
	logger.info( 'route outputs msg post ' );
	const envoi = await Outputs.generemsg( req.body, req.session.header );
	res.status( envoi.status )
		.send( {
			payload: envoi.payload
		} );
} );
/*test functionnalité
router.post('/msgtest', checkHeaders, isemailValid, async (req, res) => {
  logger.info('route outputs msg post en test');
  const envoi = await Outputstest.generemsg(req.body, req.session.header);
  res.status(envoi.status).send({
    payload: envoi.payload
  });
});
*/
router.post( '/template', checkHeaders, ( req, res ) => {
	logger.info( 'route outputs post de fichier template ' );
	// a callback can be pass to req.body to run a specific process after upload
	const saveFile = UploadFile.addjson( req.body, req.session.header );
	logger.info( saveFile );
	res.send( saveFile );
	// res.send({ status: 200, payload: { info: 'fine' } });
} );

router.post( '/pdf', checkHeaders, ( req, res ) => {
	logger.info( 'route outputs pdf post' );
	Outputs.generepdf( req.body, req.session.header )
		.then( ( doc ) => {
			res.status( doc.status )
				.download( doc.payload.data.path, doc.payload.data.name );
		} )
		.catch( ( err ) => {
			logger.info( err );
			res.status( err.status )
				.send( { payload: err.payload } );
		} );
} );


module.exports = router;
