package menu;

import game.GameMap;
import lime.ui.GamepadButton;
import lime.ui.KeyCode;
import lime.ui.KeyModifier;
import openfl.Assets;
import openfl.display.Bitmap;
import openfl.display.BitmapData;
import openfl.geom.ColorTransform;
import openfl.geom.Matrix;
import raycaster.Raycaster;

class Menu extends State {
	public var items:Array<MenuItem> = [];

	var _changed:Bool = true;

	var _gampadAccum:Float = 0;

	var bgMaze:BgMaze = new BgMaze();

	var canvas:Bitmap = new Bitmap(new BitmapData(32, 32, true, 0x00000000));

	public var selectedItem(default, set):Int;

	function set_selectedItem(value:Int):Int {
		if (value >= items.length)
			value = 0;

		if (value < 0) {
			value = items.length - 1;
		}

		for (n in 0...items.length) {
			items[n].selected = n == value;
		}

		_changed = true;

		return selectedItem = value;
	}

	public function new() {
		super();

		addChild(bgMaze);

		addChild(canvas);
	}

	override function keyDown(keyCode:KeyCode, keyModifier:KeyModifier) {
		switch (keyCode) {
			case(W | UP):
				selectedItem--;
			case(S | DOWN):
				selectedItem++;
			case(RETURN | SPACE | E):
				items[selectedItem].action();
			case _:
		}
	}

	override function update(delta:Float) {
		bgMaze.update(delta);

		if (gamepadMovement.y != 0) {
			_gampadAccum += gamepadMovement.y * 10 * delta;
			if (Math.abs(_gampadAccum) >= 1) {
				selectedItem += _gampadAccum < 0 ? -1 : 1;
				_gampadAccum = 0;
			}
		}
	}

	override function gamepadButtonDown(button:GamepadButton) {
		if (button == A) {
			items[selectedItem].action();
		}
	}

	override function render() {
		bgMaze.render();

		if (_changed) {
			canvas.bitmapData.lock();
			canvas.bitmapData.fillRect(canvas.bitmapData.rect, 0x000000ee);
			var sty:Int = Std.int((32 - items.length * 6) / 2);
			for (n in 0...items.length) {
				var item = items[n];

				var m = new Matrix();
				m.translate(Std.int((32 - item.sprite.width) / 2), sty + n * 6);

				var c = new ColorTransform();
				c.color = item.selected ? 0xffffff : 0x666666;

				canvas.bitmapData.draw(item.sprite.bitmap.bitmapData, m, c);
			}
			canvas.bitmapData.unlock();
			_changed = false;
		}
	}
}
