package app.GUI;

import app.PREPROCESSING.Parser;
import app.PREPROCESSING.ParserInterface;
import org.primefaces.model.UploadedFile;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * Created by Petr Flégl on 10.2.2017.
 */
@Named
@ManagedBean
public class FileUpload {
    public String getTable() {
        return table;
    }

    public void setTable(String table) {
        if(table!=null) this.table = table;
    }



    private String table="";


    private UploadedFile file;

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        System.out.println("set file");
        this.file = file;
    }

    public void upload(String tbl) {
        table=tbl;
        if(file!= null) {
            try {
                Path folder = Paths.get("C:\\Procesnitabulky");
                Path localFile = Files.createTempFile(folder, file.getFileName() + "-", ".csv");
                InputStream input = file.getInputstream();
                Files.copy(input, localFile, StandardCopyOption.REPLACE_EXISTING);
                Parser par = new Parser();
                if (table.equals("Table1")) {

                    par.loadDataSource(localFile.toAbsolutePath().toString(), ParserInterface.TYPE_FILE);
                    int numRows = par.getDatasetSize();

                    par.processData("app.DAO."+table);
                    par.clearData();
                    par.loadDataSource("localhost/predictorDB;Table1;predictor;predictor;"+numRows+";idvah",ParserInterface.TYPE_DB);
                    par.processData("app.DAO.Table2");
                    par.clearData();
                }else{
                    par.loadDataSource(localFile.toAbsolutePath().toString(), ParserInterface.TYPE_FILE);
                    int numRows = par.getDatasetSize();

                    par.processData("app.DAO."+table);
                    par.clearData();
                }

            } catch (IOException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            FacesMessage message = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, message);
        }
    }
}