package cz.senslog.connector.fetch.drutes;

import cz.senslog.connector.model.config.DefaultConfig;
import cz.senslog.connector.model.drutes.DrutesModel;
import cz.senslog.connector.model.drutes.PredictionData;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.*;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;

import static java.time.format.DateTimeFormatter.ofPattern;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;

class DrutesFetcherTest {

//    private static final String TEST_BASE_DIR = "predictions";
    private static final String TEST_BASE_DIR = "data";
    private static final String SUCCESS_IMPORT_FILE = "import.success";


    private String getAbsoluteTestDir() throws UnsupportedEncodingException {
        ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(Objects.requireNonNull(classLoader.getResource(TEST_BASE_DIR)).getFile());
        return URLDecoder.decode(file.getAbsolutePath(), "UTF-8");
    }

   // @AfterEach
    void cleanTest() throws Exception {
        String testBaseDir = getAbsoluteTestDir();
        Path testPath = Paths.get(testBaseDir);
        if (Files.exists(testPath)) {
            try (Stream<Path> paths = Files.walk(testPath)) {
                paths.filter(Files::isDirectory)
                        .forEach(p -> {
                            try {
                                Files.deleteIfExists(Paths.get(p.toString(), SUCCESS_IMPORT_FILE));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        });
            }
        }
    }

    @Test // happy scenario
    void fetch() throws Exception {

        DefaultConfig defaultConfig = new DefaultConfig("", null);
        defaultConfig.setProperty("baseDir", getAbsoluteTestDir());
        defaultConfig.setProperty("unitId", 4151559);
        defaultConfig.setProperty("observedDir", "current");

        DrutesConfig config = new DrutesConfig(defaultConfig);
        DrutesFetcher fetcher = new DrutesFetcher(config);
        fetcher.init();


        DrutesModel model = fetcher.fetch(Optional.empty());

        assertEquals(5_348, model.getPredictions().size());
        PredictionData predictData = model.getPredictions().get(0);
        assertEquals(4151559L, predictData.getUnitId());

        OffsetDateTime predictionFrom = LocalDateTime.of(2022, 3, 8, 23, 0,0,0)
                .atZone(ZoneId.systemDefault()).toOffsetDateTime();
        assertEquals(predictionFrom, predictData.getPredictFrom());
    }
}