package oop13.space.model;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import oop13.space.model.Score;
import oop13.space.utilities.ListIOManager;
/**
* Models the game HighScore. It's designed with Singleton pattern.
*
* @author Manuel Bottazzi
*/
public class HighScore implements Serializable {
private static final long serialVersionUID = 493387187166495267L;
private static final String FILE_PATH = "highscore.data";
private static HighScore HS = null;
private static final File F = new File(FILE_PATH);
private List<Score> scoreList = new ArrayList<>();
private transient ListIOManager<Score> scoreManager = null;
/**
* Creates a new HighScore.
*/
private HighScore() {
this.scoreManager = new ListIOManager<Score>(F);
}
/**
* Returns the HighScore, if it doesn't exit create it.
*
* @return - The HighScore
*/
public static HighScore getHighScore() {
if (HS == null) {
HS = new HighScore();
}
return HS;
}
/**
* Loads the HighScore (a List of Score) from file.
*
* @return - The list of scores
*/
public List<Score> loadHighscore() {
this.scoreList = scoreManager.readList();
if (this.scoreList != null) {
Collections.sort(scoreList);
} else {
this.scoreList = new ArrayList<>();
}
return this.scoreList;
}
/**
* Saves the current HighScore on file.
*/
private void saveHighScore() {
scoreManager.writeList(this.scoreList);
}
/**
* Adds a new entry in the current HighScore.
*
* @param name - The player name.
* @param score - The score value.
*/
public void addScore(String name, Integer score) {
Score s = new Score(name, score);
this.scoreList = scoreManager.readList();
this.scoreList.add(s);
this.saveHighScore();
}
/**
* Resets the current HighScore.
*/
public void resetHighScore() {
scoreManager.reset();
}
}