package cz.muni.disa.adamiss.se.loader;

import cz.muni.disa.adamiss.core.objects.AdamissObject;
import cz.muni.disa.adamiss.core.objects.Transaction;
import cz.muni.disa.adamiss.core.objects.TransactionFile;
import cz.muni.disa.adamiss.core.objects.impl.AdamissObjectImpl;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class DatasetLoader {
    /**
     * Function to read simple data file into TransactionFile
     *
     * @return TransactionFile with all transactions
     */
    public static TransactionFile loadDataset(String dataset) {
        final List<Transaction> transactions = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(DatasetLoader.class.getClassLoader().getResourceAsStream(dataset + ".txt")))) {
            reader.lines().forEach(
                    (line) -> {
//                        System.out.println(line);
                        String[] strings = line.split(" ");
                        List<AdamissObject> objects = new ArrayList<>();
                        for (String s : strings) {
                            objects.add(new AdamissObjectImpl(s));

                        }
                        transactions.add(new Transaction(objects));
                    }
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
        TransactionFile database = new TransactionFile(transactions);

        return database;
    }

    public static void preprocess(String file) {
        String data = "";
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(DatasetLoader.class.getClassLoader().getResourceAsStream("preprocess.txt")))) {
            String line = reader.readLine();
            while (line != null) {
                String newLine = "";
                newLine = line
                        .replaceAll(" -1", "");
                newLine = newLine.replaceAll(" -2", "");
                newLine += System.lineSeparator();
                data += newLine;
                line = reader.readLine();
            }
            reader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
//        System.out.println(data);

        File outFile = new File(file + ".txt");
        FileWriter fr = null;
        try {
            fr = new FileWriter(outFile);
            fr.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
