import color.Color;
import MapDesc.MobDesc;
import MapDesc.TileDesc;
import openfl.display.Sprite;
import openfl.events.Event;
import openfl.events.MouseEvent;
import openfl.text.TextField;

class MobCtrl extends Sprite {
	public var desc:MobDesc;

	static var colors:Map<String, Int> = [];

	public function new(desc:MobDesc) {
		super();

		this.desc = desc;

		var textName = new TextField();
		textName.text = desc.type;
		textName.selectable = false;
		textName.mouseEnabled = false;
		textName.autoSize = LEFT;
		textName.x = -textName.width / 2;
		textName.y = -textName.height / 2;
		addChild(textName);

		var color:Int;

		if (colors.exists(desc.type)) {
			color = colors[desc.type];
		} else {
			color = Color.random(255);
			colors[desc.type] = color;
		}

		graphics.beginFill(color);
		graphics.drawCircle(0, 0, TileEdit.WIDTH / 2);
		graphics.endFill();

		var deleteButton = new Sprite();
		deleteButton.graphics.beginFill(0xff0000);
		deleteButton.graphics.drawRect(-5, -5, 10, 10);
		deleteButton.graphics.endFill();
		deleteButton.buttonMode = true;

		deleteButton.x = TileEdit.WIDTH / 2;
		deleteButton.y = -TileEdit.WIDTH / 2;
		addChild(deleteButton);

		deleteButton.addEventListener(MouseEvent.CLICK, (event:MouseEvent) -> {
			dispatchEvent(new Event('delete'));
		});
	}
}

class Mobs extends Sprite {
	public var mobs:Array<MobDesc> = [];

	public function new() {
		super();
	}

	public function addMob(desc:MobDesc) {
		var ctrl = new MobCtrl(desc);
		ctrl.x = desc.x * TileEdit.WIDTH;
		ctrl.y = desc.y * TileEdit.WIDTH;
		ctrl.addEventListener('delete', (event:Event) -> {
			mobs.remove(cast(event.target, MobCtrl).desc);
			removeChild(cast(event.target, MobCtrl));
		});
		addChild(ctrl);

		mobs.push(ctrl.desc);
	}
}
