package de.frajul.endlessroll.main.screens;

import android.view.ViewGroup;
import android.widget.LinearLayout;

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.views.LevelButton;
import de.frajul.endlessroll.views.LevelButtonOnClickListener;
import de.frajul.endlessroll.views.TopBar;

/**
 * Created by Julian on 23.04.2016.
 */
public class LevelsScreen extends Screen<LinearLayout> implements LevelButtonOnClickListener {

    private LevelPack levelPack;

    private TopBar topBar;
    private LinearLayout topRow;
    private LinearLayout bottomRow;

    public LevelsScreen(GameActivity gameActivity) {
        super(ScreenType.LEVELS, gameActivity, R.layout.levels);
        topBar = super.createTopBar(R.id.levels_topbar);
        topRow = (LinearLayout) layout.findViewById(R.id.levels_top_row);
        bottomRow = (LinearLayout) layout.findViewById(R.id.levels_bottom_row);
    }

    public void onLevelPackSelected(LevelPack levelPack) {
        this.levelPack = levelPack;
    }

    private void build() {
        topRow.removeAllViews();
        bottomRow.removeAllViews();
        int levelCount = levelPack.getLevels().size();

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(15, 15, 15, 15);

        for (Level level : levelPack.getLevels())
            createButton(level, levelCount, params);
    }

    private void createButton(Level level, int levelCount, LinearLayout.LayoutParams params) {
        LevelButton button = new LevelButton(gameActivity, this, R.layout.levelbutton);
        button.init(level);

        int halfLevelCount = levelCount / 2;
        if (levelCount % 2 == 1)
            halfLevelCount++;

        if (level.getId() <= halfLevelCount)
            topRow.addView(button.getView(), params);
        else
            bottomRow.addView(button.getView(), params);
    }

    @Override
    public void prepareToBeShown() {
        topBar.update();
        build();
    }

    @Override
    public void onBackKeyDown() {
        flipTo(ScreenType.WORLDS);
    }

    @Override
    public void onClick(LevelButton levelButton) {
        Level level = levelButton.getLevel();
        if (!level.isLocked())
            gameActivity.startGame(levelPack, level);
    }
}
