view src/pathfinder/mergetest/EditorObject.java @ 157:1a2269c820df simulator2008-8-26

*** empty log message ***
author pin
date Tue, 26 Aug 2008 18:15:00 +0900
parents 09ad66f62f4a
children e9047957acc2
line wrap: on
line source

package pathfinder.mergetest;

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

import remoteeditor.command.REPCommand;
import sample.merge.TranslaterImp1;

public class EditorObject<P> {
	
	int eid;
	private ChannelSimulator<P> channel;
	private TranslaterImp1 translater;
	private List<REPCommand> sentList;
	private List<REPCommand> sendList;

	public EditorObject(int i, ChannelSimulator<P> cs) {
		// TODO Auto-generated constructor stub
		eid = i;
		channel = cs;
	}

	public EditorObject(int i, ChannelSimulator<P> cs, TranslaterImp1 imp1) {
		// TODO Auto-generated constructor stub
		eid = i;
		channel = cs;
		translater = imp1;
		sentList = new ArrayList<REPCommand>();
		sendList = new LinkedList<REPCommand>();
	}

	public ChannelSimulator<P> getChannel() {
		// TODO Auto-generated method stub
		return channel;
	}

	public int getEID() {
		// TODO Auto-generated method stub
		return eid;
	}

	public REPCommand receive(REPCommand command) {
		// TODO Auto-generated method stub
		
		if(command.eid == eid){
			if(checkReturnCommand(command)){
				REPCommand[] cmds = translater.catchOwnCommand(command);
				sendMergedCommand(cmds);
				return null;
			}else{
				sentList.add(command);
			}	
		}
		
		return command;
	}

	private boolean checkReturnCommand(REPCommand command) {
		// TODO Auto-generated method stub
		
		if(sentList.size() > 0){
			if(sentList.get(0).seq == command.seq){
				return true;
			}
		}
		
		return false;
	}

	private void sendMergedCommand(REPCommand[] cmds) {
		// TODO Auto-generated method stub
		for(int i = 0; i < cmds.length; i++){
			channel.write((P) cmds[i]);
		}
	}

	public void send(REPCommand command) {
		// TODO Auto-generated method stub
		if(false) System.out.println("send to Editor : " + eid + " : " + command);
		if(command !=null){
			//channel.write((P) command);
			write(command);
		}
	}

	public void addWaitCommand(REPCommand command) {
		// TODO Auto-generated method stub
		sendList.add(command);
	}

	public void sendWaitingCommands() {
		// TODO Auto-generated method stub
		for(REPCommand command : sendList){
			channel.write(pack(command));
		}
		sendList.clear();
	}

	private P pack(REPCommand command) {
		// TODO Auto-generated method stub
		P cmd = (P) new REPCommand(command);
		return cmd;
	}

	public void write(REPCommand cmd) {
		// TODO Auto-generated method stub
		channel.write(pack(cmd));
	}

	public boolean isMerging() {
		// TODO Auto-generated method stub
		return translater.isMerging();
	}

}