package de.samdev.colorrunner.game.world.map.provider;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.Rectangle;

import de.samdev.colorrunner.game.renderer.AbstractGameRenderer;
import de.samdev.colorrunner.game.world.CRGameWorld;
import de.samdev.colorrunner.game.world.entities.CRGameEntity;
import de.samdev.colorrunner.game.world.entities.gameentities.floor.FloorTileEntity;
import de.samdev.colorrunner.game.world.map.CRTiledMap;

public class StaticMapProvider extends MapProvider {

	private static final int CHUNK_SIZE = 16;

	private CRTiledMap map;

	private int mapRightBoundary = 0;
	public int mapPlayerPos = 0;
	public int mapMaxWidth = 0;

	public StaticMapProvider(CRTiledMap m) {
		map = m;
		mapMaxWidth = map.getWidth();
	}

	@Override
	public boolean isNextEndlessMenu(){
		return false;
	}

	@Override
	public TriggerType getTrigger(int x, int y) {
		if (x < 0) return TriggerType.NOTHING;
		if (y < 0) return TriggerType.NOTHING;
		if (x >= map.getWidth()) return TriggerType.NOTHING;
		if (y >= map.getHeight()) return TriggerType.NOTHING;

		if(map.interaktionen[x][ y] ==  CRTiledMap.GID_INTER_UP)
			return TriggerType.RUNTOP;
		else if(map.interaktionen[x][y] ==  CRTiledMap.GID_INTER_DOWN)
			return TriggerType.RUNBOTTOM;
		else if(map.interaktionen[x][y] ==  CRTiledMap.GID_INTER_RIGHT)
			return TriggerType.FLY;
		else if(map.interaktionen[x][y] == CRTiledMap.GID_INTER_MID)
			return TriggerType.GRAVITY;
		else if(map.interaktionen[x][y] == CRTiledMap.GID_INTER_END)
			return TriggerType.END;
		else if(map.interaktionen[x][y] ==  0)
			return TriggerType.NOTHING;
		else
		{
			Gdx.app.error("MapProvider", "Unknown trigger: " + map.interaktionen[x][y]);
			return TriggerType.NOTHING;
		}
	}

	@Override
	public MapProvider createNew() {
		StaticMapProvider mapProvider = new StaticMapProvider(map);
		return mapProvider;
	}

	@Override
	public void init(CRGameWorld world) {
		mapRightBoundary = appendMap(world);
	}

	private int appendMap(CRGameWorld world) {
		int height = map.getHeight();
		int width = map.getWidth();

		int xstart = mapRightBoundary;
		int xend = mapRightBoundary + CHUNK_SIZE;

		if (xend > width) xend = width;

		for (int x = xstart; x < xend; x++) {
			for (int y = 0; y < height; y++) {
				float px = x * FloorTileEntity.FLOORTILE_WIDTH;
				float py = y * FloorTileEntity.FLOORTILE_HEIGHT;

				CRGameEntity e = CRTiledMap.CreateTile(world, map.getGID(x, y), px, py);
				if (e != null) world.addEntity(e);
			}
		}

		return xend;
	}

	@Override
	public void update(CRGameWorld world, Rectangle player) {

		mapPlayerPos = 	(int)(player.x / FloorTileEntity.FLOORTILE_WIDTH);

		while (player.x + AbstractGameRenderer.MAX_GAME_WIDTH*2 > mapRightBoundary * FloorTileEntity.FLOORTILE_WIDTH && mapRightBoundary < mapMaxWidth) {
			mapRightBoundary = appendMap(world);
		}
	}
}
