package eu.jonahbauer.wizard.client.libgdx;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import eu.jonahbauer.wizard.client.libgdx.screens.MainMenuScreen;
import eu.jonahbauer.wizard.client.libgdx.util.SavedData;
import eu.jonahbauer.wizard.client.libgdx.util.SoundManager;
import eu.jonahbauer.wizard.client.libgdx.util.WizardAssetManager;
import lombok.Getter;

public class WizardGame extends Game {
	public static final boolean DEBUG = false;
	public static final int WIDTH = 1920;
	public static final int HEIGHT = 1080;

	public SpriteBatch batch;
	public WizardAssetManager assets;
	public SoundManager sounds;

	public final SavedData storage = new SavedData();

	private boolean fullscreenToggle;
	private int oldHeight, oldWidth;
	
	@Getter
	private final Client client = new Client(this);

	@Override
	public void create() {
		batch = new SpriteBatch();

		assets = new WizardAssetManager();
		assets.loadShared();
		assets.finishLoading();

		sounds = new SoundManager(assets);

		// background music
		Music backgroundMusic = assets.get(WizardAssetManager.MUSIC_BACKGROUND, Music.class);
		backgroundMusic.setLooping(true);
		backgroundMusic.setVolume(0.07f);
		backgroundMusic.play();

		// set cursor
		Pixmap cursor = assets.get(WizardAssetManager.CURSOR, Pixmap.class);
		Gdx.graphics.setCursor(Gdx.graphics.newCursor(cursor, 0, 0));
		assets.unload(WizardAssetManager.CURSOR);
		
		this.setScreen(new MainMenuScreen(this));
	}

	@Override
	public void render() {
		super.render();

		// alt + enter shortcut for fullscreen
		var enter = Gdx.input.isKeyPressed(Input.Keys.ENTER);
		var alt = (Gdx.input.isKeyPressed(Input.Keys.ALT_LEFT) || Gdx.input.isKeyPressed(Input.Keys.ALT_RIGHT));
		var toggle = enter && alt;

		if (toggle && !this.fullscreenToggle) {
			this.fullscreenToggle = true;
			var fullscreen = Gdx.graphics.isFullscreen();
			Graphics.DisplayMode displayMode = Gdx.graphics.getDisplayMode();
			if (fullscreen) {
				Gdx.graphics.setWindowedMode(oldWidth, oldHeight);
			} else {
				oldWidth = Gdx.graphics.getWidth();
				oldHeight = Gdx.graphics.getHeight();
				Gdx.graphics.setFullscreenMode(displayMode);
			}
		} else if (!toggle) {
			this.fullscreenToggle = false;
		}
	}

	@Override
	public void dispose () {
		batch.dispose();
		sounds.dispose();
		assets.dispose();
		client.shutdownNow();
		var socket = client.getSocket();
		if (socket != null) {
			socket.close();
		}
	}

}
