package presenter.io;

import model.Line;
import model.LineModel;
import presenter.Presenter;
import com.opencsv.CSVReader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.Observable;


/**
 * Implementierung verschiedener Algorithmen zur Berechnung von Ausgleichsgeraden.
 *
 * @Author: Armin Wolf
 * @Email: a_wolf28@uni-muenster.de
 * @Date: 21.06.2017.
 */
public class DataImporter extends Observable {

    private File file;
    private CSVReader reader;
    private LineModel model;
    private Presenter presenter;


    public DataImporter(File file, Presenter presenter) {
        this.model = new LineModel();
        this.presenter = presenter;
        this.presenter.setModel(this.model);
        //System.out.println(this.model.getLines().size()+ " die Anzahl der aktuellen Lines.");


        this.file = file;
        try {

            this.reader = new CSVReader(new FileReader(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void run() {

        try {
            List<String[]> lines = reader.readAll();
            int counter = 0;
            String[] result = {"import", lines.size() + "", ""};
            //System.out.println("+-------------------------------------------------------------------------------+");
            for (String[] nextLine : lines) {
                // nextLine[] is an array of values from the line
                Double x = Double.parseDouble(nextLine[1]);
                Double y = Double.parseDouble(nextLine[2]) * (-1);
                Line line = new Line(x, y);
                line.setId(counter + "");
                if (!this.presenter.getModel().getLines().contains(line)) {
                    this.presenter.getModel().addLine(line);
                }
                //System.out.format("|\t\t\t\t\t %-11d \t|\t\t\t\t\t %-11f \t|\t\t\t\t\t %-11f \t\t\t\t\t|\n", id,x,y);
                setChanged();
                counter++;
                result[2] = counter + "";
                Thread.sleep(10);
                notifyObservers(result);
            }

            //System.out.println("+-------------------------------------------------------------------------------+");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
