package przyklady_plikowe;

import java.io.*;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class McDonalds3 {
    // w tej wersji wyniki zapisuję do nowego pliku csv

    public static void main(String[] args) {
        Locale.setDefault(Locale.US);
        Pattern pattern = Pattern.compile("\\((\\d+) g\\)");

        try(BufferedReader input = new BufferedReader(new FileReader("mcdonalds.csv"));
            BufferedWriter output = new BufferedWriter(new FileWriter("mcdonalds2.csv"))) {
            String linia = input.readLine();
            String[] naglowki = linia.split(",");
            output.write(linia);
            output.write(",gramy,nasycenie");
            output.newLine();
            while((linia = input.readLine()) != null) {
                String[] dane = linia.split(",");
                Matcher matcher = pattern.matcher(dane[2]);
                if(matcher.find()) {
                    double kalorie = Double.parseDouble(dane[3]);
                    int gramy = Integer.parseInt(matcher.group(1));
                    double nasycenie = kalorie / gramy;
                    output.write(String.join(",", dane));
                    output.write(String.format(",%d,%.3f", gramy, nasycenie));
                    output.newLine();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
