package br.ufrgs.inf.prosoft.tigris.monitoring.usersession;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;

/**
 * The type Spring user getter.
 */
public class SpringUserGetter implements UserGetter {

    private final Object auth;
    /**
     * The Logger.
     */
    Logger logger = LoggerFactory.getLogger(SpringUserGetter.class);

    /**
     * Instantiates a new Spring user getter.
     *
     * @throws NoSuchMethodException     the no such method exception
     * @throws ClassNotFoundException    the class not found exception
     * @throws IllegalAccessException    the illegal access exception
     * @throws InstantiationException    the instantiation exception
     * @throws InvocationTargetException the invocation target exception
     */
    public SpringUserGetter() throws NoSuchMethodException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
        //final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName()
        Object contextHolder = Class.forName("org.springframework.security.core.context.SecurityContextHolder").newInstance();
        Object context = contextHolder.getClass().getMethod("getContext").invoke(contextHolder);
        auth = context.getClass().getMethod("getAuthentication").invoke(context);
    }

    @Override
    public String getCurrentUser() {
        try {
            return (String) auth.getClass().getMethod("getName").invoke(auth);
//        } catch (ClassNotFoundException e) {
//            logger.debug("Not able to get the current user.", e);
//        } catch (NoSuchMethodException e) {
//            logger.debug("Not able to get the current user.", e);
//        } catch (InstantiationException e) {
//            logger.debug("Not able to get the current user.", e);
//        } catch (IllegalAccessException e) {
//            logger.debug("Not able to get the current user.", e);
//        } catch (InvocationTargetException e) {
//            logger.debug("Not able to get the current user.", e);
        } catch (Exception e) {
            logger.debug("Not able to get the current user.", e);
        }
        return "Anonymous";
    }
}
