// (c) MIT 2003.  All rights reserved.

// -*-Mode: Java-*- 
// $Id: Transcript.java,v 1.2 2003/03/06 00:40:43 moltmans Exp $
// Transcript.java -- 
// Author: Michael Oltmans <moltmans@ai.mit.edu> 
// Maintainer: Michael Oltmans <moltmans@ai.mit.edu> 
// Copyright: Copyright (C) 1999 by Michael Oltmans 
// Created: <Tue Jul 20 10:59:55 1999> 
// Time-stamp: <1999-08-23 15:55:06 moltmans> 
// Keywords: 

package rec.annotate.transcript;

import java.util.*;

import rec.util.Assert;

public class Transcript
{
  protected LinkedList items;

  public Transcript( )
  {
    items = new LinkedList( );
  }

  public void addEntry( TranscriptItem item ) 
  {
    switch ( item.getAction() ) {
    case TranscriptItem.ADDED:
      addItem( item );
      break;
    case TranscriptItem.REPLACED:
      replaceItem( item );
      break;
    case TranscriptItem.REMOVED:
    case TranscriptItem.ALTERED:
      appendItem( item );
      break;
    default:
      Assert.error( "Illegal state in TranscriptItem: " + item );
    }
  }

  public void addItem( TranscriptItem item )
  {
    LinkedList l = getListForObject( item.getObject( ) );

    if ( l == null ) {
      l = new LinkedList( );
      l.addLast( item );
      items.addLast( l );
    }
    else
      Assert.note( "Added an item already in the transcript: " + item );
  }

  public void replaceItem( TranscriptItem item )
  {
    LinkedList list = getListForObject( item.getOldObject( ) );

    Assert.check( list != null, "No such object in Transcript to replace." );
    list.addLast( item );
  }
  
  public void appendItem( TranscriptItem item )
  {
    LinkedList list = getListForObject( item.getObject( ) );

    if ( list == null )
      Assert.error( "null list in transcript" );
    
    Assert.check( list != null, "No such object in Transcript to expand on." );
    list.addLast( item );
  }
  

  protected LinkedList getListForObject( Object obj ) 
  {
    LinkedList list;
    TranscriptItem item;
    Iterator it = items.listIterator( );
    
    while ( it.hasNext( ) ) {
      list = ( LinkedList ) it.next( );
      item = ( TranscriptItem ) list.getLast( );
   
      if ( obj.equals( item.getObject( ) ) ) {
	return list;
      }
    }
    return null;
  }

  public String printTranscript( )
  {
    LinkedList list;
    TranscriptItem item;
    ListIterator inner;
    ListIterator it = items.listIterator( );

    System.out.println( "==============================================" );
        
    while ( it.hasNext( ) ) {
      list = ( LinkedList ) it.next( );
      inner = list.listIterator( );
      System.out.println( ( TranscriptItem )list.getLast( ) );

      while ( inner.hasNext( ) ) {
	item = ( TranscriptItem ) inner.next( );
	System.out.println( "   " + item.toString( ) );
      }

      System.out.println( "-----------------------" );
    }

    System.out.println( "==============================================" );
    
    return "not fully implemented...";
  }
  
}



