const fs = require( 'fs-extra' );
const glob = require( 'glob' );
const path = require( 'path' );

const config = require( '../tribes/townconf.js' );

const hasAccessrighton = ( object, action, ownby ) => {
	/*
	@action (mandatory) : CRUDO
	@object (mandatory)= name of a folder object in /tribeid space can be a tree for example objects/items
  @ownby (option) = list des uuid propriétaire
	return next() if all action exist in req.app.local.tokens[UUID].ACCESSRIGHTS.data[object]
  OR if last action ="O" and uuid exist in ownBy
  Careffull if you have many action CRO let O at the end this will force req.right at true if the owner try an action on this object
	*/
	return ( req, res, next ) => {
		//logger.info( 'err.stack hasAccessrights', err.statck )
		//logger.info( `test accessright on object:${object} for ${req.session.header.xworkon}:`, req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS.data[ req.session.header.xworkon ] )
		req.right = false;
		if( req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS.data[ req.session.header.xworkon ] && req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS.data[ req.session.header.xworkon ][ object ] ) {
			req.right = true;
      [ ...action ].forEach( a => {
				if( a == "O" && ownby && ownby.includes( req.session.header.xpaganid ) ) {
					req.right = true;
				} else {
					req.right = req.right && req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS.data[ req.session.header.xworkon ][ object ].includes( a )
				}
			} )
		}
		//logger.info( 'Access data autorise? ', req.right )
		if( !req.right ) {
			return res.status( 403 )
				.send( {
					info: [ 'forbiddenAccess' ],
					model: 'middleware',
					moreinfo: 'no auth to act on this object'
				} )
		}
		next();
	}
}
module.exports = hasAccessrighton;
