package cz.vutbr.feec.burget.advanced;

import java.util.Vector;

import cz.vutbr.feec.simlib.Proc;

abstract public class Member extends Proc implements MemberActionListener {
	private final int id;
	private static int idCounter = 0;
	
	private Vector<MemberActionListener> listeners = new Vector<MemberActionListener>();
	private Vector<Member> childs = new Vector<Member>();
	private Member feedback;

	public Member() {
		this.id = idCounter++;
	}
	
	@Override
	public void action() {
		while(!getSimulation().isFinished()) {
			beforeFeedbackSent();
			innerFeedbackSent();
			afterFeedbackSent();
		}
	}

	abstract public void beforeFeedbackSent();

	public void innerFeedbackSent(){
		for (MemberActionListener l : listeners) {
			l.onFeedbackSent(this);
		}
		onFeedbackSent(feedback);
	}

	abstract public void afterFeedbackSent();
	
	public void addActionListener(MemberActionListener l) {
		listeners.add(l);
	}
	
	public void addChild(Member m) {
		childs.add(m);
		m.setFeedback(this);
	}
	
	public void removeChild(Member m) {
		childs.remove(m);
		m.setFeedback(null);
	}
	
	

	private void setFeedback(Member member) {
		this.feedback = member;
	}

	public Member getFeedback() {
		return feedback;
	}

	abstract public void onFeedbackReceived(Member m);
	
	@Override
	public String toString() {
		return "Member:"+getMemberId();
	}

	public int getMemberId() {
		return id;
	}

	public Vector<Member> getChilds() {
		return childs;
	}
}
