package com.eyeofmidas.cardtrick;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;

public class InputScreen implements Screen {

	private CardtrickGame game;

	private Vector2 startPosition;
	private Vector2 startTile;
	private DragDirection dragDirection;

	public enum DragDirection {
		LEFT, RIGHT, UP, DOWN
	};

	public InputScreen() {
		game = (CardtrickGame) Gdx.app.getApplicationListener();

		startPosition = new Vector2();
		startTile = new Vector2();
	}

	@Override
	public void render(float delta) {
		game.getStage().act(delta);

		Gdx.gl.glClearColor(0, 0, 0, 1);
		Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
		game.getStage().draw();

	}

	@Override
	public void resize(int width, int height) {
		game.getStage().getViewport().update(width, height, true);
	}

	@Override
	public void show() {
		game.getStage().clear();

		game.getStage().addListener(new InputListener() {

			@Override
			public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
				startPosition.x = x;
				startPosition.y = y;

				startTile.x = MathUtils.floor(startPosition.x / (game.getStage().getWidth() / 4));
				startTile.y = 3 - MathUtils.floor(startPosition.y / (game.getStage().getHeight() / 4));
				return true;
			}

			@Override
			public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
				Vector2 delta = new Vector2();
				delta.x = startPosition.x - x;
				delta.y = startPosition.y - y;
				if (Math.abs(delta.x) > Math.abs(delta.y)) {
					if (delta.x > 0) {
						dragDirection = DragDirection.LEFT;
					} else {
						dragDirection = DragDirection.RIGHT;
					}
				} else {
					if (delta.y < 0) {
						dragDirection = DragDirection.UP;
					} else {
						dragDirection = DragDirection.DOWN;
					}
				}
				game.goReveal(startTile, dragDirection);
			}

			@Override
			public void touchDragged(InputEvent event, float x, float y, int pointer) {
				// Gdx.app.log("EyeOfMidas", x + "," + y);
			}

			@Override
			public boolean keyDown(InputEvent event, int keyCode) {
				switch (keyCode) {
				case Input.Keys.BACK:
				case Input.Keys.ESCAPE:
					game.goMainMenu();
					break;
				}
				return false;
			}
		});

		Gdx.input.setInputProcessor(game.getStage());
		Gdx.input.setCatchBackKey(true);
	}

	@Override
	public void hide() {
		// TODO Auto-generated method stub

	}

	@Override
	public void pause() {
		// TODO Auto-generated method stub

	}

	@Override
	public void resume() {
		// TODO Auto-generated method stub

	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub

	}
}
