package de.frajul.endlessroll.main.screens;

import android.widget.RelativeLayout;

import java.util.List;

import de.frajul.endlessroll.R;
import de.frajul.endlessroll.levels.Level;
import de.frajul.endlessroll.levels.LevelPack;
import de.frajul.endlessroll.main.GameActivity;
import de.frajul.endlessroll.main.GameHandler;
import de.frajul.endlessroll.main.MyGlSurfaceView;
import de.frajul.endlessroll.main.game.Game;
import de.frajul.endlessroll.main.game.GameState;
import de.frajul.endlessroll.main.tutorial.BreakPoint;
import de.frajul.endlessroll.views.ViewManager;

/**
 * Created by Julian on 08.02.2016.
 */
public class GameScreen extends GLScreen<RelativeLayout> {

    private Game game;

    public GameScreen(GameActivity gameActivity, MyGlSurfaceView glSurfaceView) throws Exception {
        super(ScreenType.GAME, gameActivity, R.layout.game, glSurfaceView);
        game = new Game(gameViewHandler, this, gameActivity);
        glView.addRendering(game);
    }

    @Override
    public void prepareToBeShown() {
        gameActivity.getSoundManager().menuMusic.stop();

        glView.setCurrentRendering(game);
        game.getViewManager().prepareToBeShown();
    }

    public void onPause() {
        game.tryToPause();
    }

    public void setGamePausedWithoutMenu() {
        game.pauseWithoutMenu();
    }

    public void onResume() {
        game.setRunning();
    }

    public boolean isLevelFinished() {
        return game.getGameState() == GameState.LEVEL_FINISHED;
    }

    public ViewManager getGameViewManager(){
        return game.getViewManager();
    }

    @Override
    public void onBackKeyDown() {
        game.tryToPause();
        if (isLevelFinished())
            game.onGoalMessageKeyBack();
    }

    public void startGame(LevelPack levelPack, Level level) {
        game.resetViews();
        game.startGame(levelPack, level);
    }

    private GameHandler gameViewHandler = new GameHandler() {

        @Override
        public void startInUiThread(Runnable runnable) {
            gameActivity.runOnUiThread(runnable);
        }

        @Override
        public void toScreen(ScreenType screen) {
            glView.setCurrentRendering(null);
            gameActivity.flipToScreen(screen);
        }

        @Override
        public RelativeLayout getRootLayout() {
            return layout;
        }

        @Override
        public void showTutorialScreen(List<BreakPoint> breakPoints) {
            gameActivity.showTutorial(breakPoints);
        }

        @Override
        public void onException(Exception e) {
            gameActivity.onException(e);
        }
    };

}
