package prolog.syntax;

import java.io.*;
import java.util.*;
import prolog.model.*;

public class ModelScanner extends Scanner
{
	protected List listeners = new ArrayList(10);
	protected int counter = 0;

	public ModelScanner( ISymbolTable t )
	{
		super( t );
	}

	public void reset()
	{
		super.reset();
		counter = 0;
	}

	public void openDocument( File f )
		throws FileNotFoundException
	{
		this.counter = 0;
		super.openDocument( f );
	}

	public void openDocument( String text )
	{
		this.counter = 0;
		super.openDocument( text );
	}

	public void openDocument( Reader input )
	{
		this.counter = 0;
		super.openDocument( input );
	}

	public int input()
	{
		if( source == null )
			throw new RuntimeException(
				"You should open a source before parsing ;-)" );
		try
		{
			currentChar = source.read();
			currentSign++;
			if( currentChar == '\n' )
			{
				currentLine++;
				currentSign = 0;
			}
			else if( this.isCurrentWhiteSpace() )
				skipWhiteSpace();
		}
		catch( Exception ae )
		{
			ae.printStackTrace();
		}
		this.fireCharScanned( counter++ );
		return currentChar;
	}

	public void scanWord()
	{
		int begin = this.counter-1;
		currentWord.setLength (0);
		do // collect a..zA..Z0..9_
		{
			currentWord.append( (char)currentChar );
			try
			{
				currentChar = source.read();
				currentSign++;
				if( currentChar == '\n' )
				{
					currentLine++;
					currentSign = 0;
				}
				else if( this.isCurrentWhiteSpace() )
					skipWhiteSpace();
			}
			catch( Exception ae )
			{
				ae.printStackTrace();
			}
			this.fireWordScanned( begin, counter++ );
		}
		while( isCurrentChar() );
	}

	public void addScannerListener( IScannerListener l )
	{
		listeners.add( l );
	}

	public void removeScannerListener( IScannerListener l )
	{
		listeners.remove( l );
	}

	public void fireCharScanned( int index )
	{
		Iterator i = listeners.iterator();
		while( i.hasNext() )
			((IScannerListener)i.next()).charScanned( index );
	}

	public void fireWordScanned( int col1, int col2 )
	{
		Iterator i = listeners.iterator();
		while( i.hasNext() )
			((IScannerListener)i.next()).wordScanned( col1, col2 );
	}
}
