package biblioteki.csv.emps;

import java.io.File;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

public class SredniaWybranych {
    public static void main(String[] args) {
        JFileChooser chooser = new JFileChooser(".");
        chooser.setFileFilter(new FileNameExtensionFilter("Pliki CSV", "csv"));
        chooser.setDialogTitle("Wybierz plik");
        int coSieStalo = chooser.showOpenDialog(null);
        if(coSieStalo == JFileChooser.APPROVE_OPTION) {
            File wybranyPlik = chooser.getSelectedFile();
            List<Employee> employees = ObslugaCSV.wczytajPlik(wybranyPlik);
            
            Set<String> jobs = jobs(employees);
            
            String kogoSzukam = (String)JOptionPane.showInputDialog(null, "Wybierz stanowisko:", "Wybór",
            		JOptionPane.QUESTION_MESSAGE, null, jobs.toArray(), null);
            if(kogoSzukam != null) {
            	double srednia = sredniaJob(employees, kogoSzukam);
            	JOptionPane.showMessageDialog(null, "Średnia: " + srednia);
            }
        }
    }

	private static double sredniaJob(List<Employee> employees, String kogoSzukam) {
		double suma = 0;
		int ilosc = 0;
		for (Employee emp : employees) {
		    if(Objects.equals(emp.getJobTitle(), kogoSzukam)) {
		        suma += emp.getSalary();
		        ilosc++;
		    }
		}
		return suma / ilosc;
	}

	private static Set<String> jobs(List<Employee> employees) {
		Set<String> jobs = new TreeSet<>();
		for (Employee emp : employees) {
			jobs.add(emp.getJobTitle());
		}
		return jobs;
	}
}
