package com.uoc.educationalVG.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import com.uoc.educationalVG.framework.FileIO;

/**
 * Keeping Track of User Choices and High Scores
 * @author "Beginning Android 4 Games Development"
 *
 */
public class Settings {
	
	/*
	 * Whether sound effects are played back
	 */
	private static boolean soundEnabled = true; 
	
	/*
	 * The high scores are stored in a five-element integer array, sorted from
	 * highest to lowest.
	 */
	public static int[] highscores = new int[] { 100, 80, 50, 30, 10 };

	/*
	 * Tries to load the settings from a file called .memorycon from the
	 * external storage.
	 */
	public static void load(FileIO files) {
		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(
					files.readFile(".memorycon013")));
			soundEnabled = Boolean.parseBoolean(in.readLine());
			for (int i = 0; i < 5; i++) {
				highscores[i] = Integer.parseInt(in.readLine());
			}
		} catch (IOException e) {
			// :( It's ok we have defaults
		} catch (NumberFormatException e) {
			// :/ It's ok, defaults save our day
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
			}
		}
	}

	/**
	 * #Keeping Track of User Choices and High Scores# It takes the current
	 * settings and serializes them to the .memorycon file on the external
	 * storage (that is, /sdcard/.memorycon). The sound setting and each
	 * high-score entry is stored as a separate line in that file, as expected
	 * by the load() method. If something goes wrong, we just ignore the failure
	 * and use the default values defined earlier.
	 */
	public static void save(FileIO files) {
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(
					files.writeFile(".memorycon013")));
			out.write(Boolean.toString(soundEnabled));
			out.write("\n");
			for (int i = 0; i < 5; i++) {
				out.write(Integer.toString(highscores[i]));
				out.write("\n");
			}

		} catch (IOException e) {
		} finally {
			try {
				if (out != null)
					out.close();
			} catch (IOException e) {
			}
		}
	}

	/**
	 * Adds a new score to the high scores, automatically re-sorting them
	 * depending on the value we want to insert.
	 */
	public static void addScore(int score) {
		for (int i = 0; i < 5; i++) {
			if (highscores[i] < score) {
				for (int j = 4; j > i; j--)
					highscores[j] = highscores[j - 1];
				highscores[i] = score;
				break;
			}
		}
	}

	public static boolean isSoundEnabled() {
		return soundEnabled;
	}

	public static void setSoundEnabled(boolean soundEnabled) {
		Settings.soundEnabled = soundEnabled;
	}

	public static int[] getHighscores() {
		return highscores;
	}

	public static void setHighscores(int[] highscores) {
		Settings.highscores = highscores;
	}
}
