/*
 * @(#)ConvertSingleLog.java
 *
 * Copyright (C) 2004 Matt Albrecht
 * groboclown@users.sourceforge.net
 * http://groboutils.sourceforge.net
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 */

package net.sourceforge.groboutils.codecoverage.v2.util;

import net.sourceforge.groboutils.codecoverage.v2.IChannelLogger;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.IOException;


/**
 * A way to convert the single log style (not necessarily a file), and outputs
 * it to a channel logger.  This converter handles multiple channels.
 * <p>
 * As of 2004-Jun-03, the format has changed.
 *
 * @author    Matt Albrecht <a href="mailto:groboclown@users.sourceforge.net">groboclown@users.sourceforge.net</a>
 * @version   $Date: 2004/07/07 09:39:11 $
 * @since     April 16, 2004
 */
public class ConvertSingleLog
{
    private IChannelLogger channels[];
    
    /**
     * Create a new converter, using the given initialized loggers as the
     * output channels.  The order matters: each logger index refers to
     * that specific channel index; so ch[1] refers to channel 1.
     *
     * @param ch the channels to output the single log to.
     * @exception IllegalArgumentException if <tt>ch</tt> or any entry inside
     *      <tt>ch</tt> is null, or if the length of <tt>ch</tt> is <tt>0</tt>.
     */
    public ConvertSingleLog( IChannelLogger ch[] )
    {
        if (ch == null)
        {
            throw new IllegalArgumentException("no null args");
        }
        
        int len = ch.length;
        if (len <= 0)
        {
            throw new IllegalArgumentException("must pass at least one channel");
        }
        this.channels = new IChannelLogger[ len ];
        for (int i = 0; i < len; ++i)
        {
            if (ch[i] == null)
            {
                throw new IllegalArgumentException("channel "+i+" is null");
            }
            this.channels[i] = ch[i];
        }
    }
    
    
    /**
     * Loads all data from the given reader and parses it out to the
     * channels.  The reader is closed on return.
     *
     * @exception IOException if there is an I/O error reading from <tt>r</tt>.
     * @exception IllegalArgumentException if the reader is <tt>null</tt>.
     */
    public void read( Reader r, boolean ignoreFormatErrors )
            throws IOException
    {
        if (r == null)
        {
            throw new IllegalArgumentException("no null args");
        }
        
        BufferedReader br = new BufferedReader( r );
        try
        {
            String line;
            while ((line = br.readLine()) != null)
            {
//System.out.println("-- processing line ["+line+"]");
                processLine( line, ignoreFormatErrors );
            }
        }
        finally
        {
            br.close();
            r.close();
        }
    }
    
    
    /**
     * Process a single line from the single file.  Invalid formatted lines
     * will cause an I/O exception.  Blank lines are ignored.  Whitespace
     * is also ignored.
     *
     * @param line the input line
     * @exception IOException if there's a problem with the format of the line,
     *      or if <tt>line</tt> is <tt>null</tt>.
     */
    public void processLine( String line, boolean ignoreFormatErrors )
            throws IOException
    {
        if (line == null)
        {
            throw new IOException("End of stream: line is null");
        }
        line = line.trim();
        if (line.length() <= 0)
        {
            // ignore empty lines.
            return;
        }
        
        try
        {
            int pos[] = { 0, 0 };
            int channel = (int)nextShort( pos, line ); 
            
            // test the channel
            if (channel < 0)
            {
                throw new IOException( "Invalid channel: requested "+
                    channel+", but we're restricted to "+this.channels.length+
                    " channels." );
            }
            if (channel >= this.channels.length)
            {
                if (ignoreFormatErrors)
                {
                    return;
                }
                // don't ignore the error
                throw new IOException( "Invalid channel: requested "+
                    channel+", but we're restricted to "+this.channels.length+
                    " channels." );
            }
            
            // process the rest of the line
            String classID = nextElement( pos, line );
            String s = lastElement( pos, line );
            HexUtil.TwoShorts ts = new HexUtil.TwoShorts();
            
            // method then mark
            if (!HexUtil.getInstance().parseTwoHex( s, ts, ' ', 0 ))
            {
                throw new IOException( "invalid format for hexidecimal ["+
                    line+"]" );
            }
            
            // don't cover the line unless there were no format errors
//System.out.println("-- Covering channel "+channel+" ["+classID+"]["+ts.a+"]["+ts.b+"]");
            this.channels[ channel ].cover( classID, ts.a, ts.b );
        }
        catch (IOException ioe)
        {
            if (!ignoreFormatErrors)
            {
                throw ioe;
            }
            // else ignore the errors
        }
    }
    
    
    protected String nextElement( int pos[], String line )
            throws IOException
    {
        pos[1] = line.indexOf( ',', pos[0] );
        if (pos[1] <= pos[0])
        {
            throw new IOException( "invalid format ["+line+"]" );
        }
        String ret = line.substring( pos[0], pos[1] ).trim();
        pos[0] = pos[1] + 1;
        return ret;
    }
    
    
    protected short nextShort( int pos[], String line )
            throws IOException
    {
        String s = nextElement( pos, line );
        return parseShort( s, line );
    }
    
    
    protected String lastElement( int pos[], String line )
            throws IOException
    {
        if (pos[0] >= line.length())
        {
            throw new IOException( "invalid format ["+line+"]" );
        }
        String s = line.substring( pos[0] );
        return s;
    }
    
    
    protected short parseShort( String txt, String line )
            throws IOException
    {
        try
        {
            return Short.parseShort( txt );
        }
        catch (NumberFormatException e)
        {
            throw new IOException( "invalid format for short ["+line+"]" );
        }
    }
}

