package pracownicy;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

// Przerabiam klasę na wykorzystanie biblioteki Apache Commons CSV
public class ObslugaCSV {
	private static final CSVFormat format = CSVFormat.EXCEL.withDelimiter(';');
	
	public static List<Employee> wczytajPlik(File plik)  {
		List<Employee> lista = new ArrayList<>();
		try(Reader input = new BufferedReader(new FileReader(plik));
			CSVParser parser = new CSVParser(input, format)) {
			
			for(CSVRecord record : parser) {
				Employee emp = new Employee(Integer.parseInt(record.get(0)),
						record.get(1), record.get(2), record.get(3),
						Integer.parseInt(record.get(4)), LocalDate.parse(record.get(5)),
						record.get(6), record.get(7), record.get(8), record.get(9), record.get(10));
				lista.add(emp);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return lista;
	}
	
	public static void zapiszPlik(List<Employee> lista, File plik)  {
		try(Writer output = new BufferedWriter(new FileWriter(plik));
			CSVPrinter printer = new CSVPrinter(output, format)) {
			
			for(Employee emp : lista) {
				printer.printRecord(emp.getId(), emp.getFirstName(), emp.getLastName(), emp.getJobTitle(),
						emp.getSalary(), emp.getHireDate(), emp.getDepartmentName(),
						emp.getStreetAddress(), emp.getPostalCode(), emp.getCity(), emp.getCountry());
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
