import openfl.display.Bitmap;
import openfl.display.Sprite;
import openfl.events.MouseEvent;
import openfl.text.TextField;

class TextureItem extends Sprite {
	public var texture:String;

	public var selection:Sprite = new Sprite();

	public function new(editor:Main, texture:String) {
		super();

		this.texture = texture;
		var bmp = new Bitmap(editor.bitmaps[texture]);
		bmp.width = TileEdit.WIDTH;
		bmp.height = TileEdit.HEIGHT;
		addChild(bmp);

		selection.graphics.lineStyle(2, 0xff0000);
		selection.graphics.drawRect(0, 0, TileEdit.WIDTH, TileEdit.HEIGHT);
		selection.visible = false;
		selection.mouseEnabled = false;
		addChild(selection);

		buttonMode = true;
	}
}

class Textures extends Sprite {
	var items:Array<TextureItem> = [];

	public var selected:String;

	var editor:Main;

	public function new(editor:Main, title:String, textures:Array<String>) {
		super();

		this.editor = editor;

		var label = new TextField();
		label.text = title;
		label.selectable = false;
		label.autoSize = LEFT;
		addChild(label);

		for (texture in textures) {
			var item = new TextureItem(editor, texture);
			item.y = height;
			item.addEventListener(MouseEvent.CLICK, select);
			addChild(item);
			items.push(item);
		}

		var notexture = new Sprite();
		notexture.graphics.beginFill(0xffffff);
		notexture.graphics.lineStyle(1, 0xff0000);
		notexture.graphics.drawRect(0, 0, TileEdit.WIDTH, TileEdit.HEIGHT);
		notexture.graphics.moveTo(0, 0);
		notexture.graphics.lineTo(TileEdit.WIDTH, TileEdit.HEIGHT);
		notexture.graphics.moveTo(TileEdit.WIDTH, 0);
		notexture.graphics.lineTo(0, TileEdit.HEIGHT);
		notexture.buttonMode = true;
		notexture.addEventListener(MouseEvent.MOUSE_DOWN, (event:MouseEvent) -> {
			editor.mode = Tiles;
			selected = null;
			for (otherItem in items) {
				otherItem.selection.visible = false;
			}
		});
		notexture.y = height;
		addChild(notexture);
	}

	function select(event:MouseEvent) {
		editor.mode = Tiles;
		selected = cast(event.target, TextureItem).texture;

		for (otherItem in items) {
			otherItem.selection.visible = otherItem == event.target;
		}
	}
}
