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' );
// 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 config = require( '../tribes/townconf.js' );
const isAuthenticated = ( req, res, next ) => {
	/*
	  check if authenticated with valid token
	  if not => set req.session.header.xauth=1
	   if yes => set for xWorkon
	      req.session.header.accessrights={
				app:{'tribeid:website':[liste of menu]},
	      data:{  "sitewebsrc": "RWCDO",
	              "contacts": "RWCDO"}}
	    Liste of menu is linked with the app tht have to be consistent with accessrights.data
	    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
	*/
	logger.info( 'isAuthenticated()?' );
	//logger.info( 'req.app.locals.tokens', req.app.locals.tokens )
	//logger.info( 'req.session.header', req.session.header );
	// Check if token exist or not
	req.session.header.accessrights = { app: "", data: {} }
	if( req.session.header.xpaganid == config.devnoauthxuuid && req.session.header.xauth == config.devnoauthxauth ) {
		logger.info( 'isAuthenticated yes: carrefull using a bypass password give you accessrights={}' );
	} else if( req.session.header.xpaganid == "1" || !req.app.locals.tokens[ req.session.header.xpaganid ] ) {
		logger.info( `isAuthenticated no : uuid=1 (value=${req.session.header.xpaganid}) or locals.tokens[uuid] empty ` );
		logger.info( 'req.app.locals.tokens de xpaganid', req.app.locals.tokens[ req.session.header.xpaganid ] );
		logger.info( 'list key uuid de req.app.locals.tokens', Object.keys( req.app.locals.tokens ) )
		req.session.header.xauth = "1"
	} else if( req.app.locals.tokens[ req.session.header.xpaganid ].TOKEN !== req.session.header.xauth ) {
		// logger.info(req.session.header.xuuid);
		// logger.info(req.session.header.xauth);
		// update tokens from file in case recently logged
		try {
			logger.info( 'token not in list of token (req.app.locals.tokens) try to refresh from file' );
			req.app.locals.tokens = jsonfile.readFileSync( `${config.tmp}/tokens.json` );
		} catch ( err ) {
			logger.info( `check isAuthenticated issue in reading ${config.tmp}/tokens.json` );
		}
		if( req.app.locals.tokens[ req.session.header.xpaganid ].TOKEN !== req.session.header.xauth ) {
			// if still does not exist then out
			logger.info( 'isAuthenticated no, token outdated' );
			req.session.header.xauth = "1"
			req.session.header.xpaganid = "1"
		}
	}
	if( req.session.header.xauth == "1" ) {
		//return res.status( 403 )
		return res.status( 403 )
			.send( {
				info: [ 'forbiddenAccess' ],
				model: 'Pagans',
				moreinfo: 'isAuthenticated faill'
			} )
	} else {
		logger.info( 'isAuthenticated yes' );
		if( req.app.locals.tokens[ req.session.header.xpaganid ] ) {
			//logger.info( `accessright pour ${req.session.header.xpaganid}`, req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS );
			//set header.accessrights from tokens.json
			req.session.header.accessrights = req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS
		} else {
			// case of bypass no accessright available
			req.session.header.accessrights = {}
		}
		// Once per day, clean old token
		const currentday = moment()
			.date();
		logger.info( 'test si menagedone' + currentday, !fs.existsSync( `${config.tmp}/menagedone${currentday}` ) )
		if( !fs.existsSync( `${config.tmp}/menagedone${currentday}` ) ) {
			glob.sync( `${config.tmp}/menagedone*` )
				.forEach( f => {
					fs.remove( f, ( err ) => {
						if( err ) {
							logger.info( 'err remove menagedone', err )
						}
					} )
				} );
			glob.sync( `${config.tmp}/mdcreator*.log` )
				.forEach( f => {
					fs.remove( f, ( err ) => {
						if( err ) {
							logger.info( 'err remove mdcreator log', err )
						}
					} )
				} );
			const newtokens = {};
			for( const k of Object.keys( req.app.locals.tokens ) ) {
				try {
					const decodedToken = jwt.decode( req.app.locals.tokens[ k ].TOKEN, config.jwtSecret );
					//logger.info( moment( decodedToken.expiration ), moment() )
					//logger.info( moment( decodedToken.expiration ) >= moment() )
					if( moment( decodedToken.expiration ) >= moment() ) {
						newtokens[ k ] = req.app.locals.tokens[ k ];
					}
				} catch ( err ) {
					logger.info( "Check isAuthenticated cleaning token ", err );
				}
			};
			req.app.locals.tokens = newtokens;
			jsonfile.writeFileSync( `${config.tmp}/tokens.json`, newtokens );
			fs.writeFileSync( `${config.tmp}/menagedone${currentday}`, 'fichier semaphore to clean data each day can be deleted with no consequence', 'utf-8' );
		}
		next();
	}
};
module.exports = isAuthenticated;
