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

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class PlateFileReader {

    private List<List<Integer[]>> wells = new ArrayList<>();

    public PlateFileReader(String filename){

        if(!filename.matches(".*\\.csv")){
            filename = filename + ".csv";
        }

        CSVFormat plateFileFormat = CSVFormat.Builder.create()
                .setCommentMarker('#')
                .build();

        try(//don't need to close reader bc of try-with-resources auto-closing
            BufferedReader reader = Files.newBufferedReader(Path.of(filename));
            CSVParser parser = new CSVParser(reader, plateFileFormat);
        ){
            for(CSVRecord record: parser.getRecords()) {
                List<Integer[]> well = new ArrayList<>();
                for(String s: record) {
                    if(!"".equals(s)) {
                        String[] intString = s.replaceAll("\\[", "")
                                .replaceAll("]", "")
                                .replaceAll(" ", "")
                                .split(",");
                        //System.out.println(intString);
                        Integer[] arr = new Integer[intString.length];
                        for (int i = 0; i < intString.length; i++) {
                            arr[i] = Integer.valueOf(intString[i]);
                        }
                        well.add(arr);
                    }
                }
                wells.add(well);
            }
        } catch(IOException ex){
            System.out.println("plate file " + filename + " not found.");
            System.err.println(ex);
        }

    }

    public List<List<Integer[]>> getWells() {
        return wells;
    }

}