import dfl.all;
import util;
import game;
import output;

class GUI : Form
{
	private {
		Game g;
		int cell;
		int turn = 0;

		Font font;
		Color[char] colors;
		string[char] render;
	}

	this(Game g)
	{
		noMessageFilter();
		this.setStyle(ControlStyles.OPAQUE, true);
		this.g = g;

		this.paint ~= &my_paint;
		this.keyDown ~= &my_keydown;

		const MAX_SIZE = 640;
		this.formBorderStyle = FormBorderStyle.FIXED_DIALOG;
		this.maximizeBox = false;
		this.minimizeBox = false;
		this.cell = MAX_SIZE / max(g.map.W, g.map.H);
		this.clientSize = Size(g.map.W*cell, g.map.H*cell);
		set_text();

		// Resources
		this.font = new Font("MS Gothic", cell-2, GraphicsUnit.PIXEL);
		this.backColor = Color(255,255,255);
		this.colors['#'] =
		this.colors['.'] = Color(255,191,127);
		this.colors['*'] = Color(255,127,127);
		this.colors['R'] = Color(128,128,0);
		this.colors['D'] = Color(255,0,0); // Dead
		this.colors['\\'] =
		this.colors['L'] =
		this.colors['O'] = Color(127,255,127);
		this.colors['W'] = Color(204,229,255); // water

		this.render['#'] = "■";
		this.render['*'] = "✹";
		this.render['.'] = "♒";
		this.render['\\'] = "λ";
		this.render['R'] = "☃";
		this.render['D'] = "☠";
		this.render['L'] = "☒";
		this.render['O'] = "☐";
	}

private:
	void my_paint(Control, PaintEventArgs ev)
	{
		const scrH = this.clientSize.height;
		const scrW = this.clientSize.width;
		Graphics gr = new MemoryGraphics(scrW, scrH, ev.graphics);
		scope(exit) {
			gr.copyTo(ev.graphics, Rect(0,0,scrW,scrH));
			gr.dispose();
		}

		// Fill bg.
		gr.fillRectangle(this.backColor, Rect(0,0,scrW,scrH));

		// Fill water.
		int w = g.water_level();
		gr.fillRectangle(this.colors['W'], Rect(0, scrH-cell*w-1, scrW, cell*w+1));

		// Paint map.
		for(int y=1; y<=g.map.H; ++y)
		for(int x=1; x<=g.map.W; ++x) {
			Rect r = Rect(cell*(x-1), scrH-cell*y, cell, cell);
			char c = g.map[y,x];
			if( c != ' ' ) {
				if( c == 'R' && g.dead )
					c = 'D';
				gr.drawText(this.render[c], font, this.colors[c], r);
			}
		}
	}

	void my_keydown(Control c, KeyEventArgs ev)
	{
		switch(ev.keyCode)
		{
		case Keys.DOWN:  g.command('D'); break;
		case Keys.UP:    g.command('U'); break;
		case Keys.LEFT:  g.command('L'); break;
		case Keys.RIGHT: g.command('R'); break;
		case Keys.W:     g.command('W'); break;
		case Keys.A:     g.command('A'); break;
		default:         break;
		}
		if(g.cleared)
			Application.exit();
		invalidate();
		set_text();
	}

	void set_text() {
		this.text = .text("Score: ", g.score, " Air: ", g.hp, " Tide: ", g.water_until_rise);
	}
}

void main(string[] args)
{
	auto g = Game.load(File(args[1]));
	g.set_output(new StdOutput);
	auto myForm = new GUI(g);
	Application.run(myForm);
}
