/*
 *  Copyright 2002-2009 Mikhail Kryshen <mikhail@kryshen.net>
 *
 *  This file is part of BMTron.
 *
 *  BMTron 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 3 of the License, or
 *  (at your option) any later version.
 *
 *  BMTron 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.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with BMTron.  If not, see <http://www.gnu.org/licenses/>.
 */
 
package kryshen.bmtron;

import java.awt.Color;

/**
 * Computer player classes extends this class.
 */
public abstract class ThreadedPlayer extends Player implements Runnable {
    // TEST
    /** 
     * Synchronious mode (for testing).
     */
    private final static boolean SYNC_MODE = false;

    private Thread thread = null;
    private Object monitor = new Object();
    
    ThreadedPlayer(Field field, String name, Color color, int team) {
	super(field, name, color, team);
    }

    synchronized void start() {        
	if (SYNC_MODE) {
	    super.start();
	    move();
	} else {
	    thread = new Thread(this);            
	    thread.start();
	    super.start();
	}
    }
    
    synchronized void stop() {
	if (SYNC_MODE) {
	    super.stop();
	} else {
	    thread = null;
	    update();
	    super.stop();
	}
    }
    
    void update() {
	if (SYNC_MODE) {
	    move();
	} else {
	    synchronized (monitor) {
		monitor.notifyAll();
	    }
	}
    }
        
    public void run() {
	while (Thread.currentThread() == thread) {
	    
	    move();
	    
	    try {
		synchronized (monitor) {		   
		    monitor.wait();
		}
	    } catch (InterruptedException e) {}
	}
    }
    
    protected abstract void move();
}
