import util;
import game;
import driver;
import core.stdc.signal;

class NilOutput : GameObserver
{
	this(in Game g) {}
	override void on_game_changed(char c, in Game g, bool finished) {}
}

class StdOutput : GameObserver
{
	this(in Game g) {}
	override void on_game_changed(char c, in Game g, bool finished)
	{
		stdout.write(c);
		stdout.flush();
	}
}

class GuardedOutput : GameObserver
{
	this(in Game g)
	{
		setup_sigint_handling();
		ideal_log ~= g.score_if_abort_now;
		flushed = false;
	}

	override void on_game_changed(char c, in Game g, bool finished)
	{
		if(flushed)
			return;

		log ~= c;
		score_log ~= g.score;
		ideal_log ~= g.score_if_abort_now;
		if(finished || log.length+1==g.map.W*g.map.H)
			flush();
	}

private:
	string log;
	long[] score_log;
	long[] ideal_log;
	bool   flushed;

	void flush()
	{
		Tuple!(long, int, int) cand;
		cand[0] = long.min;

		for(int i=0; i<score_log.length; ++i)
			if(cand[0] < score_log[i])	
				cand = tuple(score_log[i],i,0);
		for(int i=0; i<ideal_log.length; ++i)
			if(cand[0] < ideal_log[i])	
				cand = tuple(ideal_log[i],i,1);

		if(cand[2]==0) {
			string str = log[0..cand[1]+1];
			std.c.stdio.printf("%.*s\n", str.length, str.ptr);
		} else {
			string str = log[0..cand[1]];
			std.c.stdio.printf("%.*sA\n", str.length, str.ptr);
		}
		std.c.stdio.fflush(std.c.stdio.stdout);
		flushed = true;
	}

private:
	static __gshared GuardedOutput g_output;

	void setup_sigint_handling()
	{
		assert(g_output is null);
		g_output = this;
		extern(C) static void catch_sigint(int) { g_output.flush(); application_exit(); }
		core.stdc.signal.signal(SIGINT, &catch_sigint);
	}
}
