package net.kldp.logviewer.model;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.util.ListenerList;

public class LogViewerGroup extends LogViewer {
	private long groupSeq = 0l;
	private String name = "";

	private List entries;

	private LogViewerGroup parent;

	private ListenerList listeners;
	
	public LogViewerGroup(LogViewerGroup group, long groupSeq, String name) {
		this.parent = group;
		this.groupSeq = groupSeq;
		this.name = name;
	}

	
	public String getName() {
		return this.name;
	}


	public LogViewerGroup getParent() {
		return this.parent;
	}

	public void rename(String newName) {
		this.name = newName;
		fireContactsChanged(null);
	}

	public void addEntry(LogViewer entry) {
		if (entries == null)
			entries = new ArrayList(5);
		entries.add(entry);
		fireContactsChanged(null);
	}

	public void removeEntry(LogViewer entry) {
		if (entries != null) {
			entries.remove(entry);
			if (entries.isEmpty())
				entries = null;
		}
		fireContactsChanged(null);
	}

	public LogViewer[] getEntries() {
		if (entries != null)
			return (LogViewer[]) entries.toArray(new LogViewer[entries.size()]);
		return new LogViewer[0];
	}

	public void addContactsListener(ILogListener listener) {
		if (parent != null)
			parent.addContactsListener(listener);
		else {
			if (listeners == null)
				listeners = new ListenerList();
			listeners.add(listener);
		}
	}

	public void removeContactsListener(ILogListener listener) {
		if (parent != null)
			parent.removeContactsListener(listener);
		else {
			if (listeners != null) {
				listeners.remove(listener);
				if (listeners.isEmpty())
					listeners = null;
			}
		}
	}

	protected void fireContactsChanged(LogViewerEntry entry) {
		if (parent != null)
			parent.fireContactsChanged(entry);
		else {
			if (listeners == null)
				return;
			Object[] rls = listeners.getListeners();
			for (int i = 0; i < rls.length; i++) {
				ILogListener listener = (ILogListener) rls[i];
				listener.logChanged(this, entry);
			}
		}
	}

	public long getGroupSeq() {
		return groupSeq;
	}

	public void setGroupSeq(long groupSeq) {
		this.groupSeq = groupSeq;
	}
}
