const express = require( 'express' );
const path = require( 'path' );
// Classes
const Messages = require( '../models/Messages.js' );
// Middlewares ( prefix, object ) => {
const checkHeaders = require( '../middlewares/checkHeaders' );
const isAuthenticated = require( '../middlewares/isAuthenticated' );
const hasAccessrighton = require( '../middlewares/hasAccessrighton' );
const router = express.Router();

router.post( '/', checkHeaders, ( req, res ) => {
	/*
	add message to (no authentification and accessright needs) :
	a tribeid or uuid => create a contact based on email.json or phone.json or email_phone.json
  if req.body.orderuuid exist then it store the req.body in /orders/orderuuid.json an order with state = order
	*/
	// check if a receiver is well identify if not then it send message to all user tribeid to inform **
	if( !req.body.desttribeid ) req.body.desttribeid = req.session.header.xworkon;
	if( !req.body.lang ) req.body.lang = req.session.header.xlang;
	logger.info( '/messages t send for ', req.session.header.xworkon );
	//logger.info(' Content: ',req.body);
	const result = Messages.postinfo( req.body );
	res.status( result.status )
		.send( result.data )
} );

router.put( '/:objectname/:uuid', checkHeaders, isAuthenticated, ( req, res ) => {
	// message that will create an object and sendback an email.
	// if objectnane/uuid_lg.json exist ans accessright is ste to U for the user then it replace object data with req.body.key value
	// if does not exist and accessright C then it create it with uuid
	// then if req.body.tplmessage => render email with data
	// No data management are done here, if need you can add plugin to create a workflow based object
	// if need specific data check => req.body.callback={tribeidpugin,pluginname,function} will run pluginname.function(data) add data run specific stuf before saved the message object in /objectname/data.uuid_lg/json
	let result;
	logger.info( "object", req.params.objectname )
	if( req.params.objectname == 'notifications' ) {
		//uuid is a timestamp
		req.body.time = req.params.uuid;
		result = Messages.notification( req.body, req.session.header );
	} else {
		req.body.uuid = req.params.uuid;
		req.body.object = req.params.objectname;
		result = Messages.object( req.body, req.session.header );
	}
	//logger.info( 'result', result );
	res.status( result.status )
		.json( result.data )
} );

router.get( '/user', checkHeaders, isAuthenticated, ( req, res ) => {
	// run agregate for tribeid concerned
	//
	logger.info( "request notifiation for user", req.session.header.xpaganid );
	const app = {
		tribeid: req.session.header.xapp.split( ':' )[ 0 ],
		website: req.session.header.xapp.split( ':' )[ 1 ],
		lang: req.session.header.xlang
	};
	res.send( Messages.request( req.session.header.xtribe, req.session.header.xpaganid,
		req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS, app ) );
} );

module.exports = router;
