/*
 *  @(#)PathHistoryImpl.java
 *
 * Copyright (C) 2002-2003 Matt Albrecht
 * groboclown@users.sourceforge.net
 * http://groboutils.sourceforge.net
 *
 *  Part of the GroboUtils package at:
 *  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.mbtf.v1.engine;


import net.sourceforge.groboutils.mbtf.v1.IState;
import net.sourceforge.groboutils.mbtf.v1.IValidate;
import net.sourceforge.groboutils.mbtf.v1.ITransition;
import net.sourceforge.groboutils.mbtf.v1.IPathHistory;
import net.sourceforge.groboutils.mbtf.v1.IErrors;

import java.util.Vector;

import org.apache.log4j.Logger;


/**
 * Records the states and transition history during a path traversal.
 * The instance can be cloned for the cases of errors and warnings needing to
 * store the path history when they occured.  The instance should also support
 * a toString() method for easy debugging and logging.
 *
 * @author     Matt Albrecht <a href="mailto:groboclown@users.sourceforge.net">groboclown@users.sourceforge.net</a>
 * @version    $Date: 2003/02/10 22:52:26 $
 * @since      June 12, 2002
 */
public class PathHistoryImpl implements IPathHistory, Cloneable
{
    private static final Logger LOG = Logger.getLogger( PathHistoryImpl.class );
    
    private static interface IHistoryPart
    {
        public String toString();
    }
    
    private static class StateHistoryPart implements IHistoryPart
    {
        private IState state;
        
        public StateHistoryPart( IState s )
        {
            this.state = s;
        }
        
        public String toString()
        {
            if (this.state == null)
            {
                return "    finished terminal state.\n";
            }
            return "    entered state '"+this.state.getName()+"'\n";
        }
    }
    
    private static class TransHistoryPart implements IHistoryPart
    {
        private ITransition trans;
        
        public TransHistoryPart( ITransition t )
        {
            this.trans = t;
        }
        
        public String toString()
        {
            return "    followed transition '"+this.trans.getName()+"'\n";
        }
    }
    
    private static abstract class ValidHistoryPart implements IHistoryPart
    {
        protected String err;
        
        public ValidHistoryPart( IValidate v, IErrors e )
        {
            if (e != null && e.getErrors().length > 0)
            {
                this.err = e.toString();
            }
            else
            {
                this.err = "No errors.";
            }
        }
    }
    
    private static class StateValidHistoryPart extends ValidHistoryPart
    {
        private IState state;
        
        public StateValidHistoryPart( IValidate v, IState s, IErrors e )
        {
            super( v, e );
            this.state = s;
        }
        
        public String toString()
        {
            return "    validated state '" + this.state.getName() + "': " +
                this.err + "\n";
        }
    }
    
    private static class TransValidHistoryPart extends ValidHistoryPart
    {
        private ITransition trans;
        
        public TransValidHistoryPart( IValidate v, ITransition t, IErrors e )
        {
            super( v, e );
            this.trans = t;
        }
        
        public String toString()
        {
            return "    validated transition '" + this.trans.getName() + "': " +
                this.err + "\n";
        }
    }
    
    
    
    private int errorCount = 0;
    private Vector history = new Vector();
    
    
    /**
     * When the current state changes, add the new state here.  This should
     * be called for the start state, and once at the end of every successful
     * transition.
     */
    public void addState( IState s )
    {
        LOG.debug( "addState( "+s+" )" );
        this.history.addElement( new StateHistoryPart( s ) );
        LOG.debug( "  - History is now: "+toString() );
    }
    
    
    /**
     * When a transition is about to occur, it should be added here.
     */
    public void addTransition( ITransition t )
    {
        LOG.debug( "addTransition( "+t+" )" );
        this.history.addElement( new TransHistoryPart( t ) );
    }
    
    
    /**
     * After a validation call, the error results should be added here.
     */
    public void addValidate( IValidate val, IState owningState,
            IErrors errors )
    {
        LOG.debug( "addValidate( "+val+", "+owningState+", "+errors+" )" );
        if (errors != null)
        {
            this.errorCount += errors.getErrors().length;
        }
        this.history.addElement( new StateValidHistoryPart( val, owningState,
            errors ) );
    }
    
    
    /**
     * After a validation call, the error results should be added here.
     */
    public void addValidate( IValidate val, ITransition owningTransition,
            IErrors errors )
    {
        LOG.debug( "addValidate( "+val+", "+owningTransition+", "+errors+" )" );
        if (errors != null)
        {
            this.errorCount += errors.getErrors().length;
        }
        this.history.addElement( new TransValidHistoryPart( val,
            owningTransition, errors ) );
    }
    
    
    /**
     * Returns the total number of errors (halts, failures, and errors)
     * registered during validation and transitions.
     */
    public int getErrorCount()
    {
        return this.errorCount;
    }
    
    
    public String toString()
    {
        IHistoryPart hp[] = new IHistoryPart[ this.history.size() ];
        this.history.copyInto( hp );
        if (hp.length <= 0)
        {
            return "[no history]";
        }
        StringBuffer sb = new StringBuffer("[Path History:\n");
        for (int i = 0; i < hp.length; ++i)
        {
            sb.append( hp[i] );
        }
        sb.append("\n]");
        return sb.toString();
    }
    
    
    protected Object clone()
            throws CloneNotSupportedException
    {
        PathHistoryImpl phi = (PathHistoryImpl)super.clone();
        phi.errorCount = this.errorCount;
        phi.history = (Vector)this.history.clone();
        
        return phi;
    }
    
    
    public IPathHistory copy()
    {
        try
        {
            return (IPathHistory)clone();
        }
        catch (CloneNotSupportedException e)
        {
            throw new IllegalStateException( e.toString() );
        }
    }
}

