import res.Scene;
import res.collisions.Collider;
import res.input.Key;
import res.input.KeyboardEvent;
import res.input.MouseEvent;
import res.text.Textmap;
import res.tools.MathTools.wrapi;

class MainMenu extends Scene {
	static final MENU_LEFT:Int = 10;
	static final MENU_TOP:Int = 20;

	var textmap:Textmap;

	var items = ['Новая Игра', 'Выход'];
	var currentItem(default, set):Int = 0;

	function set_currentItem(val:Int) {
		if (val != currentItem) {
			currentItem = val;

			audioMixer.play(res.rom.audioBuffers['menu']);
		}
		return currentItem;
	}

	override function init() {
		textmap = res.createTextmap(res.rom.fonts['russian']);
		add(textmap);

		updateItems();
	}

	function updateItems() {
		for (p => item in items) {
			textmap.textAt(MENU_LEFT, MENU_TOP + p, '${p == currentItem ? '>' : ' '} $item');
		}
	}

	function go() {
		switch (currentItem) {
			case 0:
				res.setScene(Game, true);
			case 1:
				res.poweroff();
		}
	}

	override function mouseEvent(event:MouseEvent) {
		switch (event) {
			case DOWN(_):
				go();
			case _:
		}
	}

	override function keyboardEvent(event:KeyboardEvent) {
		switch (event) {
			case KEY_DOWN(keyCode):
				switch keyCode {
					case Key.UP:
						currentItem = wrapi(currentItem - 1, 2);
						updateItems();
					case Key.DOWN:
						currentItem = wrapi(currentItem + 1, 2);
						updateItems();
					case Key.ENTER:
						go();
				}
			case _:
		}
	}

	override function update(dt:Float) {
		var mw = 0.;

		for (item in items) {
			if (item.length > mw)
				mw = item.length;
		}

		for (p => item in items) {
			final w = (mw + 2) * 8;
			final h = 8;

			final cx = (MENU_LEFT * 8) + w / 2;
			final cy = (MENU_TOP * 8) + p * 8 + 4;

			final result = Collider.collide(RECT(cx, cy, w, h), CIRCLE(res.mouse.x, res.mouse.y, 0));

			switch (result) {
				case OFFSET(_):
					currentItem = p;
					updateItems();
				case _:
			}
		}
	}
}
