package jp.kirikiri.tjs2;

import java.util.Iterator;
import java.util.Vector;


class LocalNamespace {
	private VectorWrap<LocalSymbolList> mLevels;
	private int mMaxCount;
	private int mCurrentCount;
	private MaxCountWriter mMaxCountWriter;

	public LocalNamespace() {
		mMaxCount = 0;
		mCurrentCount = 0;
		mLevels = new VectorWrap<LocalSymbolList>();
	}
	public void setMaxCountWriter( MaxCountWriter writer ) {
		mMaxCountWriter = writer;
	}
	public int getCount() {
		int count = 0;
		Iterator<LocalSymbolList> iter = mLevels.iterator();
		while( iter.hasNext() ) {
			LocalSymbolList list = iter.next();
			count += list.getCount();
		}
		return count;
	}
	public void push() {
		mCurrentCount = getCount();
		mLevels.add( new LocalSymbolList(mCurrentCount) );
	}
	public void pop() {
		LocalSymbolList list = mLevels.lastElement();
		commit();
		mCurrentCount = list.getLocalCountStart();
		mLevels.remove(mLevels.size()-1);
		list = null;
	}
	public int find( final String name ) {
		Iterator<LocalSymbolList> iter = mLevels.iterator();
		while( iter.hasNext() ) {
			LocalSymbolList list = iter.next();
			int lindex = list.find( name );
			if( lindex != -1 ) {
				return lindex + list.getLocalCountStart();
			}
		}
		return -1;
	}
	public int getLevel() { return mLevels.size(); }
	public void add( final String name ) {
		LocalSymbolList top = getTopSymbolList();
		if( top == null ) return;
		top.add( name );
	}
	public void remove( final String name ) {
		Iterator<LocalSymbolList> iter = mLevels.iterator();
		while( iter.hasNext() ) {
			LocalSymbolList list = iter.next();
			int lindex = list.find( name );
			if( lindex != -1 ) {
				list.remove( name );
				return;
			}
		}
	}
	public void commit() {
		int count = 0;
		Iterator<LocalSymbolList> iter = mLevels.iterator();
		while( iter.hasNext() ) {
			LocalSymbolList list = iter.next();
			count += list.getCount();
		}
		if( mMaxCount < count ) {
			mMaxCount = count;
			if( mMaxCountWriter != null ) mMaxCountWriter.setMaxCount(count);
		}
	}
	public LocalSymbolList getTopSymbolList() {
		if( mLevels.size() == 0 ) return null;
		return mLevels.lastElement();
	}
	public void clear() {
		while( mLevels.size() > 0 ) pop();
	}
	public int getMaxCount() { return mMaxCount; }
}
