package org.hso.ecommerce.supplier;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.hso.ecommerce.supplier.data.Supplier;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class ConfigurationReader {

    public static List<Supplier> read() throws IOException {
        File dir = new File("./config/");

        System.out.println("Loading Config in " + dir.getAbsolutePath());
        ArrayList<Supplier> ret = Files.list(dir.toPath()).map(path -> {

            System.out.println("Iterating over; " + path);
            if (path.toString().endsWith(".json")) {
                try {
                    String jsonData = Files.readString(path, StandardCharsets.UTF_8);
                    ObjectMapper objectMapper = new ObjectMapper();
                    Supplier sup = objectMapper.readValue(jsonData, Supplier.class);
                    System.out.println("Loaded " + sup.id);
                    return sup;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("Skipping because of file extension.");
            }
            return null;
        }).collect(Collectors.toCollection(ArrayList::new));

        ret.removeIf(Objects::isNull);

        return ret;
    }
}

