package bot;
import controller.GameController;
import controller.PlayersController;
import launch.Parameters;
import model.GameModelHistory;
import model.IModel;
import model.ModelProxy;
import org.apache.log4j.Logger;
import streams.StreamCommutator;
import streams.StreamsContainer;
import util.ClassName;
import java.io.*;
import static launch.GameLauncher.*;
public class BotManager {
private static final Logger logger = Logger.getLogger(ClassName.getCurrentClassName());
private final StreamCommutator usrCommutator;
private final GameController botGameController;
private final PipedInputStream pipedInputStream = new PipedInputStream();
private PipedOutputStream pipedOutputStream;
public BotManager(Parameters parameters, StreamsContainer container) {
logger.debug("creating bot manager with parameters: " + parameters + " container: " + container);
createPipedStream();
usrCommutator = createStreamCommutator(container);
logger.debug("creating model and proxy model");
IModel model = new GameModelHistory(parameters.getFieldSize(), parameters.getWinLineLen());
ModelProxy proxy = new ModelProxy(model);
logger.debug("creating controllers");
PlayersController controller = createPlayersController(usrCommutator, parameters.getFirstPlayer());
controller.disablePlayerSwitch();
botGameController = new GameController(proxy, null, controller);
logger.debug("creating new bot");
Bot bot = new RandomBot(new PrintStream(pipedOutputStream), proxy);
logger.debug("bot manager created");
}
private StreamCommutator createStreamCommutator(StreamsContainer container) {
logger.debug("creating user-side stream commutator");
StreamCommutator commutator = new StreamCommutator();
commutator.addStreams(pipedOutputStream, pipedInputStream, StreamCommutator.REMOTE);
commutator.addStreams(container);
return commutator;
}
private void createPipedStream() {
logger.debug("creating piped stream");
try {
pipedOutputStream = new PipedOutputStream(pipedInputStream);
} catch (IOException e) {
logger.error("catch exception ", e);
System.exit(1);
}
}
public StreamCommutator getUsrCommutator() {
return usrCommutator.reverseOrder();
}
public void startBot() {
Thread botThread = new Thread(new Runnable() {
@Override
public void run() {
Logger threadLogger = Logger.getLogger(ClassName.getCurrentClassName());
threadLogger.debug("thread started");
try {
botGameController.beginGame();
} catch (IOException e) {
threadLogger.error("catch exception:" + e.getMessage(), e);
System.exit(1);
}
}
});
logger.debug("starting bot thread");
botThread.start();
}
}