import java.io.*;
import java.util.*;

class HighScores
{
	private Score [] scArr;
	
	public HighScores()
	{
	}
	
	// compares sc score to file's scores and writes the best ten scores to the file
	public void checkHighScore(Score sc)
	{
		try{
			scArr = readScores(sc);
		}
		catch (Exception e)
		{
			System.err.println("Error in HighScores.checkHighScore 1: "+e);
		}
		Arrays.sort(scArr);
		try{
			writeScores(10);	
		}
		catch (Exception e)
		{
			System.err.println("Error in HighScores.checkHighScore 2: "+e);
		}
	}
	public void checkHighScore(Score s1, Score s2)
	{
		// scArr = readScores(s1, s2);
		// sort 
		// writeScores.
	}
	public void printScores()
	{
		for (int c=0;c<10;c++)
			System.out.println (scArr[c]);
	}
	
	// return an array of scores from file
	private Score [] readScores(Score sc) throws Exception
	{
		scArr = new Score[11];
		//Reading file
		BufferedReader br;
		FileReader fr;
		fr = new FileReader("highscore.txt");
		br = new BufferedReader (fr);	
		
		String initial;
		String points;
		int s=0;
		for (int c=0;c<10;c++)
		{
			initial = br.readLine();
			points = br.readLine();
			
			try{
				s=Integer.parseInt(points);
			}
			catch(Exception e)
			{
				System.err.println("Error in HighScores 1: " +e);
			}
			scArr[c] = new Score(s,initial);		
		}
		scArr[10]=sc;
		java.util.Arrays.sort(scArr);
		br.close();
		return scArr;
	}
	
	/*private Score [] readScores (Score s1, Score s2)
	{
		//Reading file
		FileReader fr = new FileReader("highscore.txt");
		BufferedReader br = new BufferedReader (fr);
		String input;
		input = br.readLine();
		br.close();
		
	}
	
	*/
	
	// write scores to file
	// int s: is the size of the array that is being written
	//  		this is needed because the array is sorted in asending order
	private void writeScores(int s) throws Exception
	{
		// Writing to file
		FileWriter fw = new FileWriter ("highscore.txt");
		BufferedWriter bw = new BufferedWriter (fw);
		String tempS;
		
		
		for (int c=s;c>=0;c--)
		{
			tempS = scArr[c].getInitials();
			bw.write (tempS, 0, 3);
			bw.newLine();
		
			tempS = ""+	scArr[c].getNum();
			bw.write(tempS, 0,tempS.length());
			System.out.println(tempS);
			bw.newLine();
		}
		bw.close();
	}

}