/**
 * Route middleware - redirects to login page if the user is not authorized
 */
export const requireAuth = function(stateFnct, roles) {
	return function(nextState, replace) {
		const state = typeof stateFnct === "function" ? stateFnct() : {};
		if (!(state.auth && state.auth.authenticated)) {
			replace({
			    pathname: '/login',
			    state: { nextPathname: nextState.location.pathname }
			});
		}
	}; 
};


export const authMiddleware = cfg => store => next => action => {
	try {		
		if (/.*\_REJECTED(.*?)$/.test(action.type)) {
			const resp = action.payload["response"];
			if (!resp) {
				//no response, this should be handled later
				return next(action);
			}
			const status = resp.status;
			if (status == 401 || status == 403) {
				const url = resp.headers && resp.headers["x-url"];
				//redirect to url ?
				if (url) {
					window.location = url;
					return;
				} 

				//otherwise perform common logout
				window.location = cfg.logoutUrl || '/logout';
			}
		}
		return next(action)
	} catch (err) {
		throw err;
	}
}


export const getUser = () => (window.cfg && window.cfg.user) || {}; //TODO
export const getRoles = () => (window.cfg && window.cfg.roles) || {}; //TODO

export const hasRole = (role) => {
	let roles = getRoles();//TODO?
	if (Array.isArray(role)) {
		for (let r of role) {
			if (roles.hasOwnProperty(r)) {
				return true;
			}
		}
	} else {
		if (roles.hasOwnProperty(role)) {
			return true;
		}
	}

	return false;
};



export default {};
