import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import org.apache.log.format.Formatter;
import org.apache.log.output.AbstractOutputTarget;
import org.apache.log.LogEvent;


public class DatagramTargetFactory
    extends AbstractTargetFactory
{
    private static final String FORMAT =
        "%7.7{priority} %5.5{time}   [%8.8{category}] (%{context}): %{message}\\n%{throwable}";

    public LogTarget createTarget( final Configuration conf )
        throws ConfigurationException
    {
        InetAddress address;

        final Configuration configChild = conf.getChild( "address", false );
        if ( null == configChild )
        {
            throw new ConfigurationException( "target address not specified in the config" );
        }

        try
        {
            address = InetAddress.getByName( configChild.getAttribute( "hostname" ) );
        }
        catch ( UnknownHostException uhex )
        {
            throw new ConfigurationException( "Host specified in datagram target adress is unknown!", uhex );
        }

        int port = configChild.getAttributeAsInteger( "port" );

        final Formatter formatter = getFormatter( conf.getChild( "format", false ) );

        try
        {
            return new DatagramOutputTarget( address, port, formatter );
        }
        catch ( IOException ioex )
        {
            throw new ConfigurationException( "Failed to create target!", ioex );
        }
    }

    protected Formatter getFormatter( final Configuration conf )
    {
        final String type = conf.getAttribute( "type", "pattern" );
        final String format = conf.getValue( FORMAT );

        if( "extended".equals( type ) )
        {
            return new ExtendedPatternFormatter( format );
        }
        else if( "raw".equals( type ) )
        {
            return new RawFormatter();
        }

       return new PatternFormatter( format );
    }
}
