/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
/**
 * Created by jruiz on 7/09/15.
 */
package com.scytl.products.ov.config.logs;

import com.scytl.products.oscore.logging.api.factory.LoggingFactory;
import com.scytl.products.oscore.logging.api.writer.LoggingWriter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;

@Service
public class LoggableInjector implements BeanPostProcessor {

    @Autowired
    private LoggingFactory loggingFactory;


    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        return bean;
    }

    /**
     * 'One thing need to notice is that the real logger is created after the bean object has been initialized,
     *  which means you can NOT use logger in the constructor of the bean. Because at that time, the logger field
     *  has not be defined, you'll get NullPointerException Error.'
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessBeforeInitialization(final Object bean,
                                                  String beanName) throws BeansException {
        ReflectionUtils.doWithFields(bean.getClass(), field -> {
            // make the field accessible if defined private
            ReflectionUtils.makeAccessible(field);
            if (field.getAnnotation(Loggable.class) != null) {

                LoggingWriter loggingWriter =  loggingFactory.getLogger("splunkable");
                field.set(bean, loggingWriter);
            }
        });
        return bean;
    }
}
