import java.awt.GridLayout;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
import java.io.Serializable;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

/**
 * Okno najlepszych wyników
 * ładowane z pliku podczas uruchamiania programu
 * 
 */

public class ScoreDialog extends JDialog implements Serializable {
	String[] names;
	int[] scores;
	JLabel[] lnames;
	JLabel[] lscores;
	
	/**Tworzy sformatowane "puste" okno
	 */
	public ScoreDialog(){
		super();
		setTitle("Najlepsze wyniki");
		setResizable(false);
		setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
		
		setLayout(new GridLayout(5, 1));
		
		names = new String[5];
		scores = new int[5];
		lnames = new JLabel[5];
		lscores = new JLabel[5];		
		
		names[0] = "Kubica";
		scores[0] = 7;
		
		for(int i=0; i<5; i++){
			add(lnames[i] = new JLabel(names[i]));
			add(lscores[i] = new JLabel("["+scores[i]+"]"));
		}
	}
	
	/**Dodaje wynik do listy najlepszych wyników
	 * następnie zapisuje do pliku
	 * wywoływane przez {@link Water}
	 * 
	 * @param name nazwa/imie gracza
	 * @param points ilość zdobytych punktów
	 */
	
	public void addScore(String name, int points){
		boolean check = false;
		int index=0;
		
		if (name == null || name == "")
			name = "Anonymus";
		
		for (int i=0; i<5; i++){
			if(points > scores[i] && scores[i]<scores[index])
				index = i;
				check = true;
		}
		if(!check)
			return;
		
		scores[index] = points;
		names[index] = name;
		
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				for(int i=0; i<5; i++){
					remove(lnames[i]);
					remove(lscores[i]);
				}
				for(int i=0; i<5; i++){
					add(lnames[i] = new JLabel(names[i]));
					add(lscores[i] = new JLabel("["+scores[i]+"]"));
				}
				validate();
			}
		});
		
		try{
			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("scores.dat"));
			out.writeObject(this);
			out.close();
		}catch(Exception e){}
		
	}
}
