package de.frajul.endlessroll.main;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import java.util.List;

import de.frajul.endlessroll.entities.shapes.PlayerShape;
import de.frajul.endlessroll.entities.tools.ToolType;
import de.frajul.endlessroll.levels.Level;
import de.frajul.endlessroll.levels.LevelManager;
import de.frajul.endlessroll.levels.LevelPack;
import de.frajul.endlessroll.main.screens.GLTestScreen;
import de.frajul.endlessroll.main.screens.GameScreen;
import de.frajul.endlessroll.main.screens.LevelsScreen;
import de.frajul.endlessroll.main.screens.PlayerShapeShopScreen;
import de.frajul.endlessroll.main.screens.PreStartScreen;
import de.frajul.endlessroll.main.screens.Screen;
import de.frajul.endlessroll.main.screens.ScreenFlipper;
import de.frajul.endlessroll.main.screens.SettingsScreen;
import de.frajul.endlessroll.main.screens.StartScreen;
import de.frajul.endlessroll.main.screens.ToolShopScreen;
import de.frajul.endlessroll.main.screens.WorldsScreen;
import de.frajul.endlessroll.main.tutorial.BreakPoint;
import de.frajul.endlessroll.main.tutorial.TutorialManager;
import de.frajul.endlessroll.main.tutorial.TutorialView;
import de.frajul.endlessroll.rendering.renderer.GameRenderer;
import de.frajul.endlessroll.sounds.SoundManager;
import de.frajul.endlessroll.sqlDatabase.MyDatabase;
import de.frajul.endlessroll.user.User;
import de.frajul.endlessroll.views.LevelupMessage;
import de.frajul.endlessroll.views.TaskCompletedMessage;

/**
 * Created by Julian on 06.02.2016.
 */
public class GameActivity extends Activity implements ExceptionHandler, User.LvUpListener {

    private DataStorageHandler dataStorageHandler;
    private LevelManager levelManager;
    private SoundManager soundManager;
    private User user;
    private Typeface typeface;
    private TutorialManager tutorialManager;

    private MyGlSurfaceView glSurfaceView;
    private ScreenFlipper flipper;
    private PreStartScreen preStartScreen;
    private StartScreen startScreen;
    private GLTestScreen glTestScreen;
    private WorldsScreen worldsScreen;
    private LevelsScreen levelsScreen;
    private ToolShopScreen toolShopScreen;
    private PlayerShapeShopScreen shapeShopScreen;
    private GameScreen gameScreen;
    private SettingsScreen settingsScreen;

    private LevelupMessage levelupMessage;
    private TaskCompletedMessage taskCompletedMessage;
    private TutorialView tutorialView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            GameLog.d("OnCreate");
            super.onCreate(savedInstanceState);
            super.requestWindowFeature(Window.FEATURE_NO_TITLE);
            super.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
            if (!hasGLES20())
                throw new Exception("OpenGL ES 2.0 not supported");

            dataStorageHandler = new DataStorageHandler(this);
            dataStorageHandler.getDatabase().open();
            dataStorageHandler.getDatabase().readToolData();
            dataStorageHandler.getDatabase().close();

            user = dataStorageHandler.readUserData(this);

            soundManager = new SoundManager(this);
            soundManager.setSoundOn(dataStorageHandler.readIsSoundOn());
            soundManager.backgroundMusic.getPlayer().setLooping(true);
            soundManager.backgroundMusic.start();

            levelManager = new LevelManager(this, dataStorageHandler);
            tutorialManager = new TutorialManager(this);
            tutorialManager.getToolShopTutorial().setFinished(dataStorageHandler.readToolShopTutorialFinished());

            this.glSurfaceView = new MyGlSurfaceView(this, new GameRenderer(this));
            typeface = Typeface.createFromAsset(getAssets(), "fontBaron.ttf");

            preStartScreen = new PreStartScreen(this);
            startScreen = new StartScreen(this, glSurfaceView);
            glTestScreen = new GLTestScreen(this, glSurfaceView);
            worldsScreen = new WorldsScreen(this);
            levelsScreen = new LevelsScreen(this);
            toolShopScreen = new ToolShopScreen(this);
            shapeShopScreen = new PlayerShapeShopScreen(this);
            gameScreen = new GameScreen(this, glSurfaceView);
            settingsScreen = new SettingsScreen(this);

            levelupMessage = new LevelupMessage(this);
            taskCompletedMessage = new TaskCompletedMessage(this);
            tutorialView = new TutorialView(this);

            flipper = new ScreenFlipper(this, preStartScreen, startScreen, worldsScreen,
                    levelsScreen, gameScreen, toolShopScreen, glTestScreen, settingsScreen,
                    shapeShopScreen);
            RelativeLayout relativeLayout = new RelativeLayout(this);
            relativeLayout.addView(glSurfaceView);
            relativeLayout.addView(flipper);
            relativeLayout.addView(levelupMessage.getLayout());
            relativeLayout.addView(taskCompletedMessage.getLayout());
            relativeLayout.addView(tutorialView.getLayout());
            setContentView(relativeLayout);
        } catch (Exception e) {
            onException(e);
            return;
        }
    }

    public void exitGame() {
        super.finish();
    }

    public void flipToScreen(final Screen.ScreenType screen) {
        if (screen != Screen.ScreenType.NONE) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    flipper.showScreen(screen, flipper.getCurrentScreen().getType());
                }
            });
        }
    }

    public void onSurfaceChanged() {
        if (flipper.getCurrentScreen().getType() == Screen.ScreenType.PRE_START)
            flipToScreen(Screen.ScreenType.START);
    }

    public void onWorldSelected(LevelPack levelPack) {
        levelsScreen.onLevelPackSelected(levelPack);
    }

    public void startGame(final LevelPack levelPack, final Level level) {
        flipToScreen(Screen.ScreenType.GAME);
        gameScreen.startGame(levelPack, level);
    }

    @Override
    public void onLvUp(final int level) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                levelupMessage.show(level);
            }
        });
        tutorialManager.onLvUp(user);
    }

    public void onTasksCompleted(final List<PlayerShape> shapes) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                taskCompletedMessage.show(shapes);
            }
        });
    }

    public void showTutorial(final List<BreakPoint> breakPoints) {
        if(!gameScreen.isLevelFinished()){
            gameScreen.setGamePausedWithoutMenu();
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tutorialView.show(breakPoints);
            }
        });
    }

    public void onTutorialViewHidden() {
        if (!gameScreen.isLevelFinished())
            gameScreen.onResume();
    }

    public void resetData() {
        user.clearData();
        dataStorageHandler.writeUserData(user);
        dataStorageHandler.writeToolShopTutorialFinished(false);
        levelManager.reset();
        tutorialManager.resetAllTutorials();
        MyDatabase database = dataStorageHandler.getDatabase();
        database.open();
        database.clearLevelProgess();
        database.clearLevelPackLocked();
        for (ToolType type : ToolType.values())
            type.reset();
        database.writeToolData();
        database.close();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        try {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (tutorialView.isShowingTutorial())
                    tutorialView.onClick(null);
                else
                    flipper.getCurrentScreen().onBackKeyDown();
                return true;
            }
        } catch (Exception e) {
            onException(e);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onException(Exception e) {
        GameLog.e(e);
        super.finish();
    }

    @Override
    protected void onPause() {
        GameLog.d("OnPause");
        glSurfaceView.onPause();
        if (flipper.getCurrentScreen() == gameScreen)
            gameScreen.onPause();
        soundManager.pause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        GameLog.d("OnResume");
        glSurfaceView.onResume();
        soundManager.resume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        GameLog.d("OnDestroy");
        soundManager.destroy();

        dataStorageHandler.writeSoundOn(soundManager.isSoundOn());
        super.onDestroy();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    private boolean hasGLES20() {
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ConfigurationInfo info = am.getDeviceConfigurationInfo();
        return info.reqGlEsVersion >= 0x20000;
    }

    public User getUser() {
        return user;
    }

    public DataStorageHandler getDataStorageHandler() {
        return dataStorageHandler;
    }

    public SoundManager getSoundManager() {
        return soundManager;
    }

    public Typeface getTypeface() {
        return typeface;
    }

    public LevelManager getLevelManager() {
        return levelManager;
    }

    public TutorialManager getTutorialManager() {
        return tutorialManager;
    }
}
