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

const conf = require(`${process.env.dirtown}/conf.json`);

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
	
 need to check first a person exist with this alias in tribe     
 
    const person = fs.readJsonSync(
      `${conf.dirapi}/nationchains/tribes/${req.session.header.xtribe}/persons/${req.session.header.xalias}.json`
    );

 
 
 
 
  */

  return (req, res, next) => {
    //console.log( 'err.stack hasAccessrights', err.statck )
    //console.log( `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);
        }
      });
    }
    //console.log( 'Access data autorise? ', req.right )
    if (!req.right) {
      return res.status(403).json({
        info: "forbiddenAccessright",
        ref: "headers",
        moreinfo: {
          xpaganid: req.session.header.xpaganid,
          object: object,
          xworkon: req.session.header.xworkon,
          action: action,
        },
      });
    }
    next();
  };
};
module.exports = hasAccessrighton;
