package cz.muni.disa.adamiss.se;

import cz.muni.disa.adamiss.core.objects.TransactionFile;
import cz.muni.disa.adamiss.se.common.Dataset;
import cz.muni.disa.adamiss.se.stats.collectors.DatabaseStatCollector;
import cz.muni.disa.adamiss.se.stats.objects.DBReport;
import cz.muni.disa.adamiss.se.stats.objects.ExperimentReport;
import cz.muni.disa.adamiss.se.stats.runners.ExperimentRunner;
import cz.muni.disa.adamiss.se.structures.DatasetContainer;
import javafx.util.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static cz.muni.disa.adamiss.se.loader.DatasetLoader.loadDataset;

public class Main {
    public static Logger logger = LogManager.getLogger(Main.class);

    public static void main(String[] args) {

        logger.debug("Loading datasets.");
        List<Pair<Dataset, TransactionFile>> datasets = getDatasets();

        logger.debug("Analysing datasets.");
        List<DatasetContainer> containers = new ArrayList<>();
        List<DBReport> reports = new ArrayList<>();
        for (var pair : datasets) {
            logger.debug("Analysing: " + pair.getKey().name());
            DBReport report = getDatabaseStats(pair.getKey(), pair.getValue());
            reports.add(report);

            containers.add(new DatasetContainer(pair.getKey(), pair.getValue(), report));
        }

        SimpleDateFormat formatter = new SimpleDateFormat();
        String outputFileDate = formatter.format(new Date());

        logger.debug("Saving dataset stats.");
        String dbReportCSV = DBReport.toCSVWithHeader(reports);
        saveAsCSV(dbReportCSV.toString(), "DatasetStats" + outputFileDate);

        logger.debug("Starting experiments.");
        List<ExperimentReport> eReports = ExperimentRunner.runAll(containers);

        logger.debug("Saving experiments data.");
        ExperimentReport.generateGNUPlotFiles(eReports);



    }

    public static List<Pair<Dataset, TransactionFile>> getDatasets() {
        List<Pair<Dataset, TransactionFile>> result = new ArrayList<>();
        for (Dataset dataset : Dataset.values()) {
            result.add(new Pair<>(dataset, loadDataset(dataset.path())));
        }
        return result;
    }

    public static DBReport getDatabaseStats(Dataset dataset, TransactionFile file) {
        DatabaseStatCollector collector = new DatabaseStatCollector();
        return collector.collect(dataset, file);
    }


    public static void saveAsCSV(String data, String name) {
        try {
            FileWriter report = new FileWriter(name + ".csv");
            report.write(data);
            report.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
