const jwt = require( 'jwt-simple' );
const jsonfile = require( 'jsonfile' );
const fs = require( 'fs-extra' );
const moment = require( 'moment' );
const glob = require( 'glob' );
const path = require( 'path' );

// A REMPLACER PAR hasAccessrighton.js
/*
qui permet de passer en parametre des tests d'actions autoriser sur une objet

*/


// Check if package is installed or not to pickup the right config file
const src = ( __dirname.indexOf( '/node_modules/' ) > -1 ) ? '../../..' : '..';
const config = require( path.normalize( `${__dirname}/${src}/config.js` ) );

const haveAccessrighttoanobject = ( req, res, next ) => {
	/*
		from isAuthenticated req.session.header.accessrights={app:{'tribeid:projet':profile},
	  data:{  "sitewebsrc": "RWCDO",
	          "contacts": "RWCDO"}}
		from the last successfull authentification.
	    profile is a keyword menu available into clientconf.json of tribeid
	    data, list of object accessright Read Write Create Delete Owner
	    a xuuid can read any objet if R
	    if O wner means that it can only read write its object create by himself

	 This middleware check that we apply RESTFull CRUD concept depending of access right of a xuuid trying to act onto a xworkon tribeid
	 Action get = Read put = Update post = Create delete = Delete
	 object = req.Urlpath.split(/)[0]
   */
	logger.info( 'haveAccessrighttoanobject()?' );
	// req.originalUrl contain /object/action/id  object id to run action
	// req.route.methods ={ put:true, delete:true post:true, get:true }
	const objet = req.baseUrl.slice( 1 ); //contain /object
	const model = objet.charAt( 0 )
		.toUpperCase() + objet.slice( 1 ); // model u object with first letter in uppercase
	let droit = "";
	let ownby = [];
	/*
	 Check if object exist and get the OWNBY array, not relevant for referentials object that is only manage by CRUD no Owner logic
	*/
	if( objet != "referentials" ) {
		if( !fs.existsSync( `${config.tribes}/${req.session.header.xworkon}/${objet}/${req.params.id}.json` ) ) {
			res.status( 404 )
				.send( {
					payload: {
						info: [ 'idNotfound' ],
						model,
						moreinfo: `${config.tribes}/${req.session.header.xworkon}/${objet}/${req.params.id}.json does not exist `
					}
				} );
		} else {
			ownby = jsonfile.readFileSync( `${config.tribes}/${req.session.header.xworkon}/${objet}/${req.params.id}.json` )
				.OWNBY;
		}
	}
	//logger.info( req.session.header )
	if( req.session.header.xpaganid == config.devnoauthxuuid ) {
		logger.info( 'haveAccessrighttoanobject yes cause dev test user' );
	} else {
		// accessrights was load from isAuthenticated.js middleware to make it available in req.session.header to be used into route for specific access if needed mainly to filter data in the get request depending of profil and data accessright.
		if( Object.keys( req.session.header.accessrights.data )
			.includes( "Alltribeid" ) && req.session.header.accessrights.data[ "Alltribeid" ][ objet ] ) {
			droit = req.session.header.accessrights.data[ "Alltribeid" ][ objet ];
		}
		// erase rights if tribeid is specified in addition of Alltribeid
		if( ( req.session.header.accessrights.data[ req.session.header.xworkon ] ) &&
			req.session.header.accessrights.data[ req.session.header.xworkon ][ objet ] ) {
			droit = req.session.header.accessrights.data[ req.session.header.xworkon ][ objet ];
			if( ( req.route.methods.get && droit.includes( 'R' ) ) ||
				( req.route.methods.put && droit.includes( 'U' ) ) ||
				( req.route.methods.delete && droit.includes( 'D' ) ) ||
				ownby.includes( req.params.id ) ) {
				logger.info( 'haveAccessrighttoanobject yes' )
			} else if( req.route.methods.post && droit.includes( 'C' ) ) {
				logger.info( 'haveAccessrighttoanobject yes create' );
			} else {
				logger.info( 'haveAccessrighttoanobject no' )
				res.status( 403 )
					.send( {
						payload: {
							info: [ 'NoAccessrights' ],
							model,
							moreinfo: `User ${req.session.header.xpaganid} accessrights are not set to do this action`
						}
					} );
			}
		}
	}
	next();
};
module.exports = haveAccessrighttoanobject;
