package com.mathworks;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;


public class Utils {
    String fileName;

    Utils(String fileName) {
        this.fileName = fileName;
    }

    /**
     * Reads the csv file into an ArrayList for other methods to process accordingly
     *
     * @return ArrayList
     */

    public static ArrayList<double[]> readFromCsv() {
        Scanner sc = null;
        ArrayList<double[]> inputs = new ArrayList<double[]>();

        try {
            sc = new Scanner(new File("input.csv"));

            sc.useDelimiter("\n");   //sets the delimiter pattern
            sc.next();
            String line;

            while (sc.hasNext())  //returns a boolean value
            {
                line = sc.next();
                StringTokenizer tokenizer = new StringTokenizer(line, ",");
                double[] tmp = new double[tokenizer.countTokens()];
                for (int i = 0; i < tmp.length; i++) {
                    String s = tokenizer.nextToken();
                    if (s.compareTo("Inf") == 0) {
                        tmp[i] = Double.POSITIVE_INFINITY;
                    } else if (s.compareTo("-Inf") == 0) {
                        tmp[i] = Double.NEGATIVE_INFINITY;
                    } else {
                        tmp[i] = Double.parseDouble(s);
                    }
                }
                inputs.add(tmp);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally{
            sc.close();  //closes the scanner
        }

        return inputs;
    }


    /**
     * Reads the csv file prepares the data into a 2D double array
     * as expected from the deployed MATLAB function
     *
     * @return double[][]
     */
    public static double[][] prepareDataForMatrixInput(){
        ArrayList<double[]> inputs = Utils.readFromCsv();

        //The deployed MATLAB function expects a 2d array as input and hence we are converting the arraylist into
        //2D array of doubles
        double[][] inpMat = new double[inputs.size()][];
        int i = 0;
        for (double[] mat : inputs) {
            inpMat[i] = mat;
            i++;
        }
        return inpMat;
    }

}