package zero1hd.rhythmbullet.ui.components;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;

import zero1hd.rhythmbullet.controls.KeyMap;

public class KeySetter extends Actor {
	TextureRegion keyIcon;
	KeyMap keyMap;
	
	public KeySetter(final KeyMap keyMap, final String control) {
		this.keyMap = keyMap;
		keyIcon = keyMap.getIcon(keyMap.stringToID(control));
		setSize(keyIcon.getRegionWidth(), keyIcon.getRegionHeight());
		
		InputListener keyListener = new InputListener() {
			@Override
			public boolean keyUp(InputEvent event, int keycode) {
				getStage().setKeyboardFocus(null);
				Gdx.app.debug("KeySetter", "input keycode received: " + keycode);
				if (keycode != Keys.ESCAPE) {
					Gdx.app.debug("keySetter", "input has been set to: " + Keys.toString(keycode));
					if (setKey(keycode, control)) {
						keyMap.updateKeys();
						addAction(Actions.sequence(Actions.color(Color.GREEN, 0.2f), Actions.color(Color.WHITE, 0.2f)));
					} else {
						addAction(Actions.sequence(Actions.color(Color.RED, 0.2f), Actions.delay(0.1f), Actions.color(Color.WHITE, 0.2f)));
					}
				}
				return super.keyUp(event, keycode);

			}
		};
		
		addListener(keyListener);
		
	}
	
	
	public boolean setKey(int keycode, String control) {
		if (keyMap.getIcon(keycode) != null) {
			keyMap.getKeys().putInteger(control, keycode);
			keyIcon = keyMap.getIcon(keycode);
			return true;
		} else {
			return false;
		}
	}
	
	@Override
	public void draw(Batch batch, float parentAlpha) {
		batch.setColor(getColor());
		batch.draw(keyIcon, getX(), getY(), getWidth(), getHeight());
		super.draw(batch, parentAlpha);
	}
}
