/**
 * 
 */


package gov.va.med.cds.log4j;


import java.io.Serializable;

import gov.va.med.cds.log4j.persistence.LoggerPersistenceManagerInterface;

import org.apache.logging.log4j.core.*;
import  org.apache.logging.log4j.core.config.plugins.*;
import org.apache.logging.log4j.core.layout.PatternLayout;
//import org.apache.log4j.spi.LoggingEvent;
import org.springframework.context.ApplicationContext;


/**
 * @author DNS   egberb
 *
 */
@Plugin(name="SpringAwareDbAppender", category="Core", elementType="appender", printObject=true)
public class SpringAwareDbAppender
    extends
        AbstractSpringAwareProxy
{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private LoggerPersistenceManagerInterface loggerPersistenceManager;

    protected SpringAwareDbAppender(String name, Filter filter,
			Layout<? extends Serializable> layout) {
		super(name, filter, layout);
	}
    
    @PluginFactory
	public static SpringAwareDbAppender createAppender(
			@PluginAttribute("name")String name,
			@PluginElement("Filters")Filter filter,
			@PluginElement("Layout")Layout<? extends Serializable> layout)
	{	
		if(layout == null){
			layout = PatternLayout.createDefaultLayout();
		}
		return new SpringAwareDbAppender(name,filter,layout);
	}

    @Override
    public void append( LogEvent event )
    {
        ApplicationLogEvent appLogEvent = new ApplicationLogEvent( event );
        if(loggerPersistenceManager==null){
        	activateOptions();
        	if(loggerPersistenceManager != null){
        		loggerPersistenceManager.persistApplicationLogEvent( appLogEvent );
        	}
        }
        else{
        	loggerPersistenceManager.persistApplicationLogEvent( appLogEvent );
        }
    }


    //@Override
    public void activateOptions( )
    {
        ApplicationContext appContext = getApplicationContext();
        if ( appContext != null )
        {
            loggerPersistenceManager = ( LoggerPersistenceManagerInterface )appContext.getBean( "loggerPersistenceManager" );
        }

    }


    /*
     * (non-Javadoc)
     * @see org.apache.log4j.AppenderSkeleton#requiresLayout()
     */
    public boolean requiresLayout( )
    {
        return false;
    }


    //@Override
    public void close( )
    {
        // no-op
    }

}