/**
 * Highscore.java
 * Handles setting and getting highscores
 *
 * @author  Paul Krishnamurthy
 */

package com.example.flappybird;

import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

public class Highscore {
	// Read / Write to file setup
	private static final String FILE_PATH = "/res/data/highscore.dat";
	private static final URL dataURL = Highscore.class.getResource(FILE_PATH);
	private static final File dataFile;

	// Highscore
	private int bestScore;

	// Scanner
	private static Scanner dataScanner = null;

	static {
		try {
			assert dataURL != null;
			dataFile = Paths.get(dataURL.toURI()).toFile();
		} catch (URISyntaxException e) {
			throw new RuntimeException(e);
		}
	}

	public Highscore () {

		// Load scanner with data file
		try {
			dataScanner = new Scanner(dataFile);
		} catch (IOException e) {
			System.out.println("Cannot load highscore!");
		}

		// Store highscore
		bestScore = Integer.parseInt(dataScanner.nextLine());

	}

	/**
	 * @return Player's highscore
	 */
	public int bestScore () {
		return bestScore;
	}

	/**
	 * Sets new highscore in the data file
	 * @param newBest New score update
	 */
	public void setNewBest (int newBest) {
		// Set new best score
		bestScore = newBest;

		try {
			// Write new highscore to data file
			PrintWriter dataWriter = new PrintWriter(FILE_PATH, StandardCharsets.UTF_8);
			dataWriter.println(newBest);
			dataWriter.close();
		} catch (IOException e) {
			System.out.println("Could not set new highscore!");
		}

	}

}
