/*
 * @(#)XmlCombinedReportGenerator.java
 *
 * Copyright (C) 2003 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.report;

import java.io.IOException;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import net.sourceforge.groboutils.codecoverage.v2.IAnalysisMetaData;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


/**
 * Combines all the XML Reports into a single XML report.
 *
 * @author    Matt Albrecht <a href="mailto:groboclown@users.sourceforge.net">groboclown@users.sourceforge.net</a>
 * @version   $Date: 2004/04/15 05:48:26 $
 * @since     December 18, 2002
 * @see       IAnalysisMetaData
 */
public class XmlCombinedReportGenerator implements IXmlCombinedReportConst
{
    private static final org.apache.log4j.Logger LOG =
        org.apache.log4j.Logger.getLogger( XmlCombinedReportGenerator.class );
    
    
    private static final NumberFormat DFORMAT = NumberFormat.getInstance();
    private static final NumberFormat IFORMAT = NumberFormat.getInstance();
    static {
        DFORMAT.setMaximumFractionDigits( 2 );
        DFORMAT.setMinimumFractionDigits( 2 );
        IFORMAT.setMaximumFractionDigits( 0 );
    }
    
    private DocumentBuilder docBuilder = getDocumentBuilder();
    
    
    private static class Report
    {
        String measureName;
        String unitName;
        Element current;
        
        public Report( Document doc )
        {
            Element e = doc.getDocumentElement();
            if (!T_COVERAGEREPORT.equals( e.getTagName() ))
            {
                throw new IllegalArgumentException( "Document root is not "+
                    T_COVERAGEREPORT );
            }
            this.measureName = e.getAttribute( A_MEASURE );
            this.unitName = e.getAttribute( A_UNIT );
            if (this.measureName == null || this.measureName.length() <= 0
                || this.unitName == null || this.unitName.length() <= 0)
            {
                throw new IllegalArgumentException(
                    "Document root is not a proper "+T_COVERAGEREPORT );
            }
            this.current = e;
        }
        
        public Report( String mn, String un, Element c )
        {
            this.measureName = mn;
            this.unitName = un;
            this.current = c;
        }
        
        public Report getFirst( String childName )
        {
            NodeList list = this.current.getChildNodes();
            for (int i = 0; i < list.getLength(); ++i)
            {
                if (list.item(i) instanceof Element)
                {
                    Element e = (Element)list.item(i);
                    if (e.getTagName().equals( childName ))
                    {
                        return new Report( this.measureName, this.unitName, e );
                    }
                }
            }
            return null;
        }
        
        public Report[] getAll( String childName )
        {
            NodeList list = this.current.getChildNodes();
            List out = new LinkedList();
            for (int i = list.getLength(); --i >= 0;)
            {
                if (list.item(i) instanceof Element)
                {
                    Element e = (Element)list.item(i);
                    if (e.getTagName().equals( childName ))
                    {
                        out.add( new Report( this.measureName, this.unitName,
                            e ) );
                    }
                }
            }
            Report r[] = (Report[])out.toArray( new Report[ out.size() ] );
            return r;
        }
    }
    
    
    /**
     * Contains all reports at the same element depth
     */
    private static class ReportSet
    {
        private Map reports = new HashMap();
        
        public ReportSet( Document docs[] )
        {
            for (int i = 0; i < docs.length; ++i)
            {
                Report r = new Report( docs[i] );
                this.reports.put( r.measureName, r );
            }
        }
        
        public ReportSet( Report r[] )
        {
            for (int i = 0; i < r.length; ++i)
            {
                this.reports.put( r[i].measureName, r[i] );
            }
        }
        
        public ReportSet getFirst( String childName )
        {
            Iterator iter = getMeasureNames();
            List reps = new LinkedList();
            while (iter.hasNext())
            {
                Report r = getReport( (String)iter.next() );
                if (r != null)
                {
                    r = r.getFirst( childName );
                    if (r != null)
                    {
                        reps.add( r );
                    }
                }
            }
            return new ReportSet( (Report[])reps.toArray(
                new Report[ reps.size() ] ) );
        }
        
        public Report getReport( String measureName )
        {
            Object o = this.reports.get( measureName );
            if (!(o instanceof Report))
            {
                throw new IllegalStateException("Expected Report, but found "
                    +o+" ("+o.getClass()+")" );
            }
            Report r = (Report)o;
            //Report r = (Report)this.reports.get( measureName );
            /* there might be an empty measure for this sub-element.
            if (r == null)
            {
                throw new IllegalArgumentException(
                    "Unknown measure name "+measureName );
            }
            */
            return r;
        }
        
        // helper method.
        public Report nextReport( Iterator iter )
        {
            return getReport( (String)iter.next() );
        }
        
        public Iterator getMeasureNames()
        {
            return this.reports.keySet().iterator();
        }
    }
    
    
    /**
     * Create a report from the given report set.
     *
     * @return the root element generated.
     */
    public Element createReport( Document reports[] )
            throws IOException
    {
        if (reports == null)
        {
            throw new IllegalArgumentException("no null args");
        }
        
        Document doc = this.docBuilder.newDocument();
        Element rootEl = createRootNode( doc );
        
        ReportSet rootDocs = new ReportSet( reports );
        join( doc, rootEl, rootDocs );
        
        return rootEl;
    }
    
    
    private Element createRootNode( Document doc )
    {
        if (doc == null)
        {
            throw new IllegalArgumentException("no null args");
        }
        
        Element rootEl = doc.createElement( T_COVERAGEREPORT );
        doc.appendChild( rootEl );
        
        return rootEl;
    }
    
    
    private void join( Document doc, Element rootEl, ReportSet reports )
    {
        // make a top-level node that describes all the measure types
        Element moduleTypesEl = doc.createElement( T_MODULETYPES );
        rootEl.appendChild( moduleTypesEl );
        Iterator iter = reports.getMeasureNames();
        while (iter.hasNext())
        {
            Report r = reports.nextReport( iter );
            Element moduleEl = doc.createElement( T_MODULE );
            moduleTypesEl.appendChild( moduleEl );
            moduleEl.setAttribute( A_MEASURE, r.measureName );
            moduleEl.setAttribute( A_UNIT, r.unitName );
        }
        
        // join the total coverage numbers
        joinCoverage( doc, rootEl, reports.getFirst( T_COVER ) );
        
        // join the package coverage numbers
        ReportSet[] byPackage = sort( reports, T_PACKAGE, A_NAME );
        for (int i = 0; i < byPackage.length; ++i)
        {
            joinPackage( doc, rootEl, byPackage[i] );
        }
        
        // join the class coverage numbers
        ReportSet[] byClass = sort( reports, T_CLASSCOVERAGE, A_CLASSSIGNATURE );
        for (int i = 0; i < byClass.length; ++i)
        {
            joinClass( doc, rootEl, byClass[i] );
        }
    }
    
    
    private void joinClass( Document doc, Element parentEl, ReportSet reports )
    {
        Iterator iter = reports.getMeasureNames();
        if (!iter.hasNext())
        {
            throw new IllegalStateException("No class elements.");
        }
        Element classEl = doc.createElement( T_CLASSCOVERAGE );
        parentEl.appendChild( classEl );
        
        // join the coverage numbers
        joinCoverage( doc, classEl, reports.getFirst( T_COVER ) );
        
        Report r = reports.nextReport( iter );
        iter = null;
        classEl.setAttribute( A_CLASSSIGNATURE, r.current.getAttribute( A_CLASSSIGNATURE ) );
        classEl.setAttribute( A_CLASSNAME, r.current.getAttribute( A_CLASSNAME ) );
        classEl.setAttribute( A_PACKAGE, r.current.getAttribute( A_PACKAGE ) );
        classEl.setAttribute( A_SOURCEFILE, r.current.getAttribute( A_SOURCEFILE ) );
        r = null;
        
        
        // join the method coverage numbers
        ReportSet[] byMethod = sort( reports, T_METHODCOVERAGE, A_METHODSIGNATURE );
        for (int i = 0; i < byMethod.length; ++i)
        {
            joinMethod( doc, classEl, byMethod[i] );
        }
    }
    
    
    private void joinMethod( Document doc, Element parentEl, ReportSet reports )
    {
        Iterator iter = reports.getMeasureNames();
        if (!iter.hasNext())
        {
            throw new IllegalStateException("No class elements.");
        }
        
        Element methodEl = doc.createElement( T_METHODCOVERAGE );
        parentEl.appendChild( methodEl );
        boolean notSetup = true;
        while (iter.hasNext())
        {
            Report r = reports.nextReport( iter );
            if (notSetup)
            {
                methodEl.setAttribute( A_METHODSIGNATURE, r.current.getAttribute( A_METHODSIGNATURE ) );
                methodEl.setAttribute( A_METHODSIGNATURE_REAL, r.current.getAttribute( A_METHODSIGNATURE_REAL ) );
                notSetup = false;
            }
            Report marks[] = r.getAll( T_MARK );
            for (int i = 0; i < marks.length; ++i)
            {
                joinMark( doc, methodEl, marks[i] );
            }
        }
        
        // join the coverage numbers
        joinCoverage( doc, methodEl, reports.getFirst( T_COVER ) );
    }
    
    
    private void joinMark( Document doc, Element parentEl, Report mark )
    {
        // original
        //    <mark covered="true" index="10" text="Line 185" weight="0" sourceline="1" />
        Element mEl = doc.createElement( T_MARK );
        parentEl.appendChild( mEl );
        
        mEl.setAttribute( A_MEASURE, mark.measureName );
        mEl.setAttribute( A_COVERED, mark.current.getAttribute( A_COVERED ) );
        mEl.setAttribute( A_INDEX, mark.current.getAttribute( A_INDEX ) );
        mEl.setAttribute( A_TEXT, mark.current.getAttribute( A_TEXT ) );
        mEl.setAttribute( A_WEIGHT, mark.current.getAttribute( A_WEIGHT ) );
        mEl.setAttribute( A_SOURCELINE, mark.current.getAttribute( A_SOURCELINE ) );
    }
    
    
    /**
     * Join a package element together
     */
    private void joinPackage( Document doc, Element parentEl, ReportSet reports )
    {
        Iterator iter = reports.getMeasureNames();
        if (!iter.hasNext())
        {
            throw new IllegalStateException("No package elements.");
        }
        Element packageEl = doc.createElement( T_PACKAGE );
        parentEl.appendChild( packageEl );
        
        Report r = reports.nextReport( iter );
        iter = null;
        packageEl.setAttribute( A_NAME, r.current.getAttribute( A_NAME ) );
        r = null;
        
        joinCoverage( doc, packageEl, reports.getFirst( T_COVER ) );
    }
    
    private void joinCoverage( Document doc, Element parentEl, ReportSet reports )
    {
        joinCoverage( doc, parentEl, reports, false );
    }
    
    /**
     * Join the coverage numbers together.
     */
    private void joinCoverage( Document doc, Element parentEl, ReportSet reports, boolean debug )
    {
        Element coverEl = doc.createElement( T_COVER );
        parentEl.appendChild( coverEl );
        if (debug)
        {
            System.out.println("jc: Adding coverage to "+parentEl.getTagName());
        }
        
        Iterator iter = reports.getMeasureNames();
        int measureCount = 0;
        int coveredCount = 0;
        int totalCount = 0;
        double weightedPercentTotal = 0.0;
        while (iter.hasNext())
        {
            Report r = reports.nextReport( iter );
            if (debug)
            {
                System.out.println("jc: - Adding measure "+r.measureName);
                System.out.println("jc: - measure parent = "+
                    ((Element)r.current.getParentNode()).getTagName());
            }
            Element modCoverEl = doc.createElement( T_MODULECOVER );
            coverEl.appendChild( modCoverEl );
            modCoverEl.setAttribute( A_MEASURE, r.measureName );
            
            Element cur = r.current;
            ++measureCount;
            coveredCount += parseI( cur.getAttribute( A_COVERED ) );
            totalCount += parseI( cur.getAttribute( A_TOTAL ) );
            weightedPercentTotal += parseD( cur.getAttribute( A_WEIGHTEDPERCENT ) );
            
            modCoverEl.setAttribute( A_COVERED_DISP, cur.getAttribute( A_COVERED_DISP ) );
            modCoverEl.setAttribute( A_COVERED, cur.getAttribute( A_COVERED ) );
            modCoverEl.setAttribute( A_TOTAL_DISP, cur.getAttribute( A_TOTAL_DISP ) );
            modCoverEl.setAttribute( A_TOTAL, cur.getAttribute( A_TOTAL ) );
            modCoverEl.setAttribute( A_PERCENTCOVERED_DISP, cur.getAttribute( A_PERCENTCOVERED_DISP ) );
            modCoverEl.setAttribute( A_PERCENTCOVERED, cur.getAttribute( A_PERCENTCOVERED ) );
            modCoverEl.setAttribute( A_WEIGHTEDPERCENT_DISP, cur.getAttribute( A_WEIGHTEDPERCENT_DISP ) );
            modCoverEl.setAttribute( A_WEIGHTEDPERCENT, cur.getAttribute( A_WEIGHTEDPERCENT ) );
        }
        
        double perc = 100.0;
        if (totalCount > 0)
        {
            perc = (double)coveredCount * 100.0 / (double)totalCount;
        }
        
        // not totally accurate, but it works, and the value isn't used right now
        double weight = 100.0;
        if (measureCount > 0)
        {
            weight = weightedPercentTotal / (double)measureCount;
        }
        
        coverEl.setAttribute( A_COVERED_DISP, format( coveredCount )  );
        coverEl.setAttribute( A_COVERED, formatNumber( coveredCount ) );
        coverEl.setAttribute( A_TOTAL_DISP, format( totalCount ) );
        coverEl.setAttribute( A_TOTAL, formatNumber( totalCount ) );
        coverEl.setAttribute( A_PERCENTCOVERED_DISP, format( perc ) );
        coverEl.setAttribute( A_PERCENTCOVERED, formatNumber( perc ) );
        coverEl.setAttribute( A_WEIGHTEDPERCENT_DISP, format( weight ) );
        coverEl.setAttribute( A_WEIGHTEDPERCENT, formatNumber( weight ) );
    }
    
    
    //-----------------------------------------------------------------------
    // Helper / utilities
    
    
    private String format( int i )
    {
        return IFORMAT.format( (long)i );
    }
    
    
    private String format( double d )
    {
        return DFORMAT.format( d );
    }
    
    
    private String formatNumber( int i )
    {
        return Integer.toString( i );
    }
    
    
    private String formatNumber( double d )
    {
        return Double.toString( d );
    }
    
    
    private int parseI( String s )
    {
        try
        {
            return IFORMAT.parse( s ).intValue();
        }
        catch (java.text.ParseException e)
        {
            throw new IllegalStateException( "Expected an integer, but found "+
                s );
        }
    }
    
    
    private double parseD( String s )
    {
        try
        {
            return DFORMAT.parse( s ).doubleValue();
        }
        catch (java.text.ParseException e)
        {
            throw new IllegalStateException( "Expected a number, but found "+
                s );
        }
    }
    
    
    private ReportSet[] sort( ReportSet reports, String tagName,
            String attrName )
    {
        Map reportsByPackage = new HashMap();
        Iterator iter = reports.getMeasureNames();
        while (iter.hasNext())
        {
            Report r = reports.nextReport( iter );
            Report[] subs = r.getAll( tagName );
            for (int i = 0; i < subs.length; ++i)
            {
                String val = subs[i].current.getAttribute( attrName );
                List s = (List)reportsByPackage.get( val );
                if (s == null)
                {
                    s = new LinkedList();
                    reportsByPackage.put( val, s );
                }
                s.add( subs[i] );
            }
        }
        List sets = new LinkedList();
        iter = reportsByPackage.values().iterator();
        while (iter.hasNext())
        {
            List rep = (List)iter.next();
            ReportSet rs = new ReportSet( (Report[])rep.toArray(
                new Report[ rep.size() ] ) );
            sets.add( rs );
        }
        return (ReportSet[])sets.toArray( new ReportSet[ sets.size() ] );
    }
    
    
    private static DocumentBuilder getDocumentBuilder() {
        try {
            return DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (Exception exc) {
            throw new ExceptionInInitializerError(exc);
        }
    }
}

