package com.mygdx.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.mygdx.game.Character.InputController;
import com.mygdx.game.Character.Mouse;
import com.mygdx.game.Character.Player;
import com.mygdx.game.Dimension.BlockMaterials;
import com.mygdx.game.Dimension.Chunks;
import com.mygdx.game.Dimension.World;
import com.mygdx.game.Dimension.WorldRenderer;
import com.mygdx.game.UI.GUI;

import static com.mygdx.game.Restrictions.*;

public class Main extends ApplicationAdapter {
	private SpriteBatch batch;
	private WorldRenderer worldRenderer;
	private GUI gui;
	private FitViewport fitViewport;
	public static float delta = 0;
	float timeSinceLastUpdate = 0f; //accumulator
	public static OrthographicCamera cam;
	private InputController inputController;
	private Mouse mouse;
	private Player player;


	@Override
	public void create () {
		Gdx.graphics.setWindowedMode(1024,576);
		cam = new OrthographicCamera(VIEWPORT_WIDTH, VIEWPORT_HEIGHT);
		player = new Player(cam,0,0);
		fitViewport = new FitViewport(VIEWPORT_WIDTH,VIEWPORT_HEIGHT, cam);
		mouse = new Mouse();
		gui = new GUI(mouse,fitViewport);
		inputController = new InputController(player);
		worldRenderer = new WorldRenderer(mouse,inputController);
		batch = new SpriteBatch();

		BlockMaterials.create();
		Chunks.create();


		//Starting location of the player
		cam.translate(TILE_SIZE >> 1,  TILE_SIZE >> 1);
		cam.zoom = 25f;
	}

	@Override
	public void render () {
		Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);

		timeSinceLastUpdate += Gdx.graphics.getDeltaTime(); //Accumulate delta time
		batch.begin();
		if(timeSinceLastUpdate > 1/10f){
			worldRenderer.render(batch);
		}
		player.render(batch,timeSinceLastUpdate);

		delta +=Gdx.graphics.getDeltaTime();
		if(delta > RENDER_TIME) {
			delta -= RENDER_TIME;
			World.loadChunks();
			World.unloadChunks();
		}

		gui.render(batch);
		batch.end();
	}


	@Override
	public void dispose () {
		gui.dispose();
		batch.dispose();
		player.textureAtlas.dispose();
	}
}
