/*
 * Created on 24.06.2004
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *  
 */
package networkconsole.datamodel;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * @author Eugene Prokopiev <eugene_prokopiev@mail.ru>
 * 
 */
abstract public class EntryList implements IEntryAdapter {
	
	protected Set changeListeners = new HashSet();
	protected ArrayList entries = new ArrayList();
	
	public ArrayList getEntries() {
		return entries;
	}
	
	abstract public void dispose() throws EntryListException;
	
	abstract protected void load() throws EntryListException;
	
	private void clear() {		
		Iterator iterator = entries.iterator();
		while (iterator.hasNext()) {
			Entry entry = (Entry)iterator.next();
			entry.removeChangeListener();	
		}
		innerClear();
	}
	
	protected void innerClear() {
		entries.clear();
	}
	
	public void refresh() throws EntryListException {
		try {
			clear();
			load();
		} finally {		
			Iterator iterator = changeListeners.iterator();
			while (iterator.hasNext())
				((IEntryListAdapter)iterator.next()).refresh();	
		}
	}
	
	public void add(Entry entry) throws EntryListException {
		innerAdd(entry);
		Iterator iterator = changeListeners.iterator();
		while (iterator.hasNext())
			((IEntryListAdapter)iterator.next()).entryAdd(entry);
	}

	protected void innerAdd(Entry entry) {
		if (entry != null) {
			entries.add(entry);
			entry.addChangeListener(this);
		}
	}
	
	public void remove(Entry entry) throws EntryListException {
		innerRemove(entry);
		Iterator iterator = changeListeners.iterator();
		while (iterator.hasNext())
			((IEntryListAdapter)iterator.next()).entryRemove(entry);
	}

	protected void innerRemove(Entry entry) {
		if (entry != null) {
			entries.remove(entry);
			entry.removeChangeListener();
		}
	}
	
	protected void edit(Entry entry) throws EntryListException {
		if (entry != null) {
			Iterator iterator = changeListeners.iterator();
			while (iterator.hasNext())
				((IEntryListAdapter)iterator.next()).entryEdit(entry);
		}
	}
	
	public void addChangeListener(IEntryListAdapter adapter) {
		changeListeners.add(adapter);
	}
	
	public void removeChangeListener(IEntryListAdapter adapter) {
		changeListeners.remove(adapter);
	}
	
}
