package de.thdeg.greiner.superpangworld.game.managers;

import de.thdeg.greiner.superpangworld.graphics.helper.Level;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * The level manager for creating and providing levels.
 */
public class LevelManager {

    /** The amount of background images */
    private static final int BACKGROUND_IMAGE_COUNT = 9;
    /** The queue to store the generated levels */
    private final Queue<Level> levels;
    /** The list with all the background image names */
    private final List<String> backgroundImages;

    /**
     * Create a level manager.
     *
     * @param difficultyIsSetToEasy flag if easy difficulty is set
     */
    public LevelManager(boolean difficultyIsSetToEasy){
        levels = new ArrayDeque<>();
        backgroundImages = loadBackgroundImages();
        generateLevels(difficultyIsSetToEasy);
    }

    /**
     * Get the next level. If there a no remaining levels an exception is thrown.
     *
     * @return the next level
     * @throws NoMoreLevelsAvailableException if there is no level remaining
     */
    public Level getNextLevel() throws NoMoreLevelsAvailableException {
        if(levels.isEmpty()){
            throw new NoMoreLevelsAvailableException();
        }else{
            return levels.poll();
        }
    }

    /**
     * Generate the levels according to the difficulty.
     *
     * @param easyDifficulty flag if easy difficulty is set
     */
    private void generateLevels(boolean easyDifficulty){
        int overallScoreNeeded = 0;
        int imageIndex = 0;
        for(int i=0;i<99;i++){
            int scoreNeeded = easyDifficulty ? 1000 + (100*i) : 10000 + (1000*i);
            overallScoreNeeded += scoreNeeded;
            levels.add(new Level(i+1, scoreNeeded,overallScoreNeeded,backgroundImages.get(imageIndex)));
            if((i+1)%4==0){
                imageIndex++;
                if(imageIndex==BACKGROUND_IMAGE_COUNT){
                    imageIndex = 0;
                }
            }
        }
    }

    /**
     * Create the background image name list.
     *
     * @return the list with the background image names
     */
    private List<String> loadBackgroundImages(){
        List<String> images = new ArrayList<>();
        for(int i=1;i<=BACKGROUND_IMAGE_COUNT;i++){
            images.add("background_"+i+".png");
        }
        return images;
    }

    /**
     * The exception in case no next level is remaining.
     */
    public static class NoMoreLevelsAvailableException extends Exception{}
}
