package de.wwwu.awolf.presenter.data;

import de.wwwu.awolf.model.Line;
import de.wwwu.awolf.presenter.AbstractPresenter;
import de.wwwu.awolf.presenter.data.generator.CircleDatasetGenerator;
import de.wwwu.awolf.presenter.data.generator.CloudDatasetGenerator;
import de.wwwu.awolf.presenter.data.generator.LineDatasetGenerator;
import de.wwwu.awolf.presenter.data.io.DataExporter;
import de.wwwu.awolf.presenter.data.io.DataImporter;
import de.wwwu.awolf.presenter.util.Logging;

import java.io.File;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;

public class DataHandler {

    private final AbstractPresenter presenter;

    public DataHandler(AbstractPresenter presenter) {
        this.presenter = presenter;
    }

    public Set<Line> getData(final File file) {
        //Presenter soll die Klasse überwachen
        ExecutorCompletionService<Set<Line>> completionService = new ExecutorCompletionService<>(this.presenter.getExecutor());
        Logging.logDebug("Importing Data: "  + file.getAbsolutePath());
        completionService.submit(new DataImporter(file));
        //wait until future is ready
        try {
            return completionService.take().get();
        } catch (InterruptedException | ExecutionException e) {
            Logging.logError("Interrupted while importing... ", e);
            Thread.currentThread().interrupt();
            return Collections.emptySet();
        }
    }


    public Set<Line> getData(final DataType type, final int dataSize) {
        //Presenter soll die Klasse überwachen
        ExecutorCompletionService<Set<Line>> completionService = new ExecutorCompletionService<>(this.presenter.getExecutor());
        Logging.logDebug("Generating Data: Size: "  + dataSize + ", dataType: " + type.name());

        switch (type) {
            case CIRCLE:
                completionService.submit(new CircleDatasetGenerator(dataSize));
                break;
            case LINE:
                completionService.submit(new LineDatasetGenerator(dataSize));
                break;
            case CLOUD:
                completionService.submit(new CloudDatasetGenerator(dataSize));
                break;
            default:
                return Collections.emptySet();
        }

        try {
            return completionService.take().get();
        } catch (InterruptedException | ExecutionException e) {
            Logging.logError("Interrupted while generating... ", e);
            Thread.currentThread().interrupt();
            return Collections.emptySet();
        }
    }

    public void exportData(File file, Set<Line> lines) {
        this.presenter.getExecutor().submit(new DataExporter(lines, file));
    }


    public enum DataType {
        CLOUD,
        LINE,
        CIRCLE
    }


}
