package jp.ac.nii.icpc2010.tournament;

import java.io.File;

import jp.ac.nii.icpc2010.Main;
import jp.ac.nii.icpc2010.manager.OptionsManager;

public class TournamentSlave extends Thread {
	private TournamentMaster master;

	public TournamentSlave(TournamentMaster master) {
		super();
		this.master = master;
		start();
	}
	
	@Override
	public void run() {
		while (true) {
			if (!master.isAlive()) {
				break;
			}
			QueuedMatch qm = master.pollQueuedMatch();
			if (qm != null) {
				//Logger.log("round "+qm.getRound().getNumber()+": "+qm.getPlayerOne()+" vs "+qm.getPlayerTwo() + " = ...");
				File recordFile = new File("level_"+qm.getRound().getNumber()+"_rec_"+qm.getPlayerOne()+"_VS_"+qm.getPlayerTwo()+".dat");
				String[] args = new String[]{
						"-playerClass", qm.getPlayerOne().getPlayerClass(),
						"-playerClass", qm.getPlayerTwo().getPlayerClass(),
						"-cmdMode", "-record", recordFile.getAbsolutePath()
				};
				Main.main(args);
				Match m = new Match(qm.getPlayerOne(), qm.getPlayerTwo(), recordFile, new OptionsManager(args));
				qm.setMatch(m);
				qm.getGroup().addMatch(m);
				Logger.log("round "+qm.getRound().getNumber()+": "+qm.getPlayerOne()+" vs "+qm.getPlayerTwo() + " = " + m.getResult(qm.getPlayerOne()));
				master.reportFinishedMatch();
			} else {	
				try {
					sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
			}
		}
	}
}
