package de.frajul.endlessroll.levels;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

import java.util.List;

import de.frajul.endlessroll.levels.worlds.World;

/**
 * Created by Julian on 07.12.2015.
 */
@Root
public class LevelPack {

    @Attribute
    private int id;
    @Element
    private World world;
    @ElementList
    private List<Level> levels;

    private String name;
    private boolean locked = true;

    public int getId() {
        return id;
    }

    public List<Level> getLevels() {
        return levels;
    }

    public World getWorld() {
        return world;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public int getFinishedLevelCount() {
        int count = 0;
        for (Level level : levels)
            if (level.isFinished())
                count++;
        return count;
    }

    public int getCollectedStarCount() {
        int count = 0;
        for (Level level : levels)
            count += level.getCollectedStarCodeForSQL().length();
        return count;
    }

    public int getAvailableStars() {
        return levels.size() * 3;
    }

    public int getCollectedEnergyCount() {
        int count = 0;
        for (Level level : levels)
            count += level.isEnergyCollected() ? 1 : 0;
        return count;
    }

    public int getAvailableEnergy() {
        return levels.size();
    }

    public void tryToUnlockFirstLevel() {
        Level firstLevel = getLevel(1);
        if (firstLevel != null)
            firstLevel.setLocked(false);
    }

    public Level getLevel(int id) {
        for (Level level : levels)
            if (level.getId() == id)
                return level;
        return null;
    }

    public Level getNextLevel(Level currentLevel) {
        return getLevel(currentLevel.getId() + 1);
    }

    public boolean isAllLevelsFinished() {
        for (Level level : levels)
            if (!level.isFinished())
                return false;
        return true;
    }

    public boolean isLastLevel(Level level) {
        return getNextLevel(level) == null;
    }

    public void reset() {
        for (Level level : levels)
            level.reset();
        setLocked(true);
        tryToUnlockFirstLevel();
    }

    public void setLocked(boolean locked) {
        this.locked = locked;
    }

    public boolean isLocked() {
        return locked;
    }
}
