package de.frajul.endlessroll.main.game;

import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

import de.frajul.endlessroll.data.Vector;
import de.frajul.endlessroll.entities.DestroyEffect;
import de.frajul.endlessroll.entities.Obstacle;
import de.frajul.endlessroll.entities.Player;
import de.frajul.endlessroll.entities.collectables.Energy;
import de.frajul.endlessroll.entities.collectables.Star;
import de.frajul.endlessroll.entities.collision.CollisionManager;
import de.frajul.endlessroll.entities.particles.Firework;
import de.frajul.endlessroll.entities.particles.ParticleSystem;
import de.frajul.endlessroll.entities.textures.TexturePack;
import de.frajul.endlessroll.entities.tools.Bomb;
import de.frajul.endlessroll.entities.tools.Tool;
import de.frajul.endlessroll.entities.tools.ToolType;
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.GameLog;
import de.frajul.endlessroll.main.physics.Physics;
import de.frajul.endlessroll.main.screens.GameScreen;
import de.frajul.endlessroll.main.screens.Screen;
import de.frajul.endlessroll.rendering.Rendering;
import de.frajul.endlessroll.sqlDatabase.MyDatabase;
import de.frajul.endlessroll.views.ToolButton;
import de.frajul.endlessroll.views.ToolButtonBar;
import de.frajul.endlessroll.views.ViewManager;

/**
 * Created by Julian on 26.11.2015.
 */
public class Game extends Rendering<GameScene> {

    private GameActivity gameActivity;
    private GameHandler handler;
    private ViewManager viewManager;
    private LevelPack levelPack;
    private ParticleSystem particleSystem;
    private Firework firework;

    private ToolType currentTool;
    private Player player;
    private Physics physics;
    private CollisionManager collisionManager;
    private Timer timer;
    private GameState gameState = GameState.COUNTDOWN;

    private Level level;
    private List<Integer> collectedStars = new ArrayList<>();
    private boolean energyCollected;

    public Game(GameHandler handler, GameScreen gameScreen, GameActivity gameActivity) throws Exception {
        super(gameActivity);
        this.handler = handler;
        this.gameActivity = gameActivity;
        physics = new Physics();
        collisionManager = new CollisionManager(this);
        particleSystem = new ParticleSystem(getContext());
        viewManager = new ViewManager(this, gameScreen, handler, gameActivity);
    }

    @Override
    public GameScene init(TexturePack texturePack, Timer timer, boolean isFirstTime) {
        GameLog.d("init Game");
        this.timer = timer;
        try {
            if (isFirstTime) {
                scene = new GameScene(gameActivity, texturePack, particleSystem);
                firework = new Firework(particleSystem.firework, scene.getCamera());
                if (level != null)
                    startGame(levelPack, level);
            } else {
                scene.setTexturePack(texturePack);
            }
            particleSystem.loadTextures();
        } catch (Exception e) {
            onException(e);
        }
        return scene;
    }

    public void startGame(LevelPack levelPack, Level level) {
        GameLog.d("Start game");
        try {
            this.level = level;
            this.levelPack = levelPack;
            if (scene != null) {
                gameActivity.getSoundManager().getCurrentGameMusic().reset();
                gameActivity.getSoundManager().randomizeCurrentGameMusic();
                gameState = GameState.COUNTDOWN;
                gameActivity.getTutorialManager().resetGameTutorials();
                collectedStars.clear();
                energyCollected = false;
                particleSystem.deleteAllSources();
                scene.loadLevel(level, levelPack.getWorld(),
                        gameActivity.getUser().getCurrentPlayerShape());
                player = scene.getPlayer();
                viewManager.resetViews(gameActivity.getUser());
                setCurrentTool(viewManager.toolButtonBar.getActiveButton().getToolType(), true);
                viewManager.startCountdown();
            }
        } catch (Exception e) {
            onException(e);
        }
    }

    public void countdownFinished() {
        gameActivity.getSoundManager().resumeAllSounds();
        gameActivity.getSoundManager().getCurrentGameMusic().start();
        gameState = GameState.RUNNING;
    }

    @Override
    public void setScreenSize(int width, int height) {
        Vector screenSize = new Vector(width, height);
        scene.setScreenSize(screenSize);
    }

    @Override
    public void update() {
        try {
            particleSystem.update(timer);
            if (scene == null || player == null)
                return;

            float playerProgress = player.getProgress();
            float playerSpeed = player.getMovement().getX();
            viewManager.update(gameState == GameState.RUNNING, timer, playerProgress, playerSpeed);
            switch (gameState) {
                case RUNNING:
                    if (player.getPosition().y < -2f) {
                        onGameOver(false);
                        return;
                    }
                    if (player.getPosition().x >= scene.getGoalX()) {
                        onGoalReached();
                        return;
                    }
                    scene.getCamera().update(player.getPosition().y, timer);

                    gameActivity.getTutorialManager().update(level, playerProgress);

                    physics.applyGravity(scene, timer);
                    scene.update(timer);
                    collisionManager.update(physics, scene, timer);
                    break;
                case COUNTDOWN:
                    viewManager.updateCountdown(timer.getFrameTimeSeconds());
                    break;
            }
        } catch (Exception e) {
            onException(e);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (gameState == GameState.RUNNING) {
            ToolButtonBar bar = viewManager.toolButtonBar;
            ToolButton button = bar.getByToolType(currentTool);
            if (button != null && button.finishedLoading()) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (currentTool == ToolType.BOMB) {
                        try {
                            Vector touchPoint = scene
                                    .calcWorldFromScreenCoords(event.getX(), event.getY());
                            Obstacle selectedObstacle = scene.getObstacleAtPoint(touchPoint);
                            if (selectedObstacle == null) {
                                viewManager.showBombErrorMessage(event.getX(), event.getY());
                                return true;
                            } else {
                                button.setProgress(0);
                                scene.getBombSelected().set(false);
                                Tool tool = addTool(event.getX(), event.getY());
                                if (tool != null && tool instanceof Bomb)
                                    ((Bomb) tool).setAttachedObstacle(selectedObstacle);
                                return true;
                            }
                        } catch (Exception e) {
                            onException(e);
                            return true;
                        }
                    }
                    button.setProgress(0);
                    addTool(event.getX(), event.getY());
                }
            }
            return true;
        }
        return false;
    }

    public void resetViews() {
        viewManager.resetViews(gameActivity.getUser());
    }

    public void continueGame() {
        viewManager.hideShortMenu();
        gameState = GameState.COUNTDOWN;
        viewManager.startCountdown();
    }

    public void startNextLevel() {
        level = levelPack.getNextLevel(level);
        startGame(levelPack, level);
    }

    public void restartLevel() {
        startGame(levelPack, level);
    }

    public void toLevelsScreen() {
        handler.toScreen(Screen.ScreenType.LEVELS);
    }

    public void onToolButtonFinishedLoading(ToolType toolType){
        if(currentTool == ToolType.BOMB && toolType == ToolType.BOMB)
            scene.getBombSelected().set(true);
    }

    public void setCurrentTool(ToolType toolType, boolean toolButtonFinishedLoading) {
        currentTool = toolType;
        if (currentTool == ToolType.BOMB && toolButtonFinishedLoading) {
            scene.getBombSelected().set(true);
        } else {
            scene.getBombSelected().set(false);
        }
    }

    public void pauseWithoutMenu() {
        gameState = GameState.PAUSED;
    }

    public void tryToPause() {
        if (gameState == GameState.GAME_OVER || gameState == GameState.LEVEL_FINISHED || gameState == GameState.PAUSED)
            return;
        gameActivity.getSoundManager().pauseAllSounds();
        gameActivity.getSoundManager().getCurrentGameMusic().pause();
        viewManager.showShortMenu();
        if (gameState == GameState.COUNTDOWN)
            viewManager.stopCountdown();
        gameState = GameState.PAUSED;
    }

    public void onGoalMessageKeyBack() {
        viewManager.onGoalMessageKeyBack();
    }

    public void setRunning() {
        gameState = GameState.RUNNING;
    }

    private Tool addTool(float x, float y) {
        try {
            gameActivity.getSoundManager().playSound(gameActivity.getSoundManager().placeToolSound);
            return scene.addTool(currentTool, x, y, physics);
        } catch (Exception e) {
            onException(e);
        }
        return null;
    }

    public void onGameOver(boolean playerExplode) {
        gameActivity.getSoundManager().getCurrentGameMusic().stop();
        gameActivity.getSoundManager().stopAllSounds();
        gameActivity.getSoundManager().playSound(gameActivity.getSoundManager().dieSound);
        if (playerExplode) {
            scene.getUncategorizedEntities().remove(player);
            DestroyEffect.EXPLOSION.createEffect(particleSystem, player.getPosition(),
                    new Vector(player.getWidth(), player.getHeight())).start();
        }
        gameState = GameState.GAME_OVER;
        viewManager.showGameOverMessage();
    }

    private void onGoalReached() {
        gameActivity.getSoundManager().getCurrentGameMusic().stop();
        gameActivity.getSoundManager().stopAllSounds();
        gameActivity.getSoundManager().playSound(gameActivity.getSoundManager().goalSound);

        gameState = GameState.LEVEL_FINISHED;
        if (!level.isFinished())
            gameActivity.getUser().gainLvFinishedEp();
        level.setFinished(true);

        for (int i = 0; i <= 2; i++) {
            if (collectedStars.contains(i)) {
                level.setStarCollected(i, true);
                gameActivity.getUser().onStarCollected();
            }
        }

        if (energyCollected) {
            level.setEnergyCollected(true);
            gameActivity.getUser().onEnergyCollected();
        }

        firework.start();
        gameActivity.getSoundManager().playSound(gameActivity.getSoundManager().fireworkSound);

        viewManager.showGoalMessage(levelPack, level);

        MyDatabase database = gameActivity.getDataStorageHandler().getDatabase();
        database.open();
        database.writeLevelProgress(level);

        gameActivity.showNewFinishedPlayerShapeTasks();

        Level nextLevel = levelPack.getNextLevel(level);
        if (nextLevel != null) {
            nextLevel.setLocked(false);
            database.writeLevelProgress(nextLevel);
        } else {
            LevelPack nextLevelPack = gameActivity.getLevelManager().getNextLevelPack(levelPack);
            if (nextLevelPack != null) {
                nextLevelPack.setLocked(false);
                database.writeLevelPackLocked(nextLevelPack);
            }
        }
        database.close();
        gameActivity.getDataStorageHandler().writeUserData(gameActivity.getUser());
    }

    public void onStarCollision(Star star) {
        if (!star.isDestroyed()) {
            scene.onStarCollision(star);
            gameActivity.getSoundManager()
                    .playSound(gameActivity.getSoundManager().collectStarSound);
            collectedStars.add(star.getIndex());
        }
    }

    public void onEnergyCollision(Energy energy) {
        if (!energy.isDestroyed()) {
            scene.onEnergyCollision(energy);
            gameActivity.getSoundManager()
                    .playSound(gameActivity.getSoundManager().collectEnergySound);
            energyCollected = true;
        }
    }

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

    public GameState getGameState() {
        return gameState;
    }

    public ViewManager getViewManager() {
        return viewManager;
    }
}
