package de.hftstuttgart.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.stream.Collectors;

public class BackendUtil {

    /**
     * Loop through all {@link File}s in {@code filesFromZipFile} and find {@link File} {@code fileNameToSearchFor}. <br>
     * And return a {@link List} of Strings for each line in file {@code fileNameToSearchFor}
     *
     * @param filesFromZipFile all files which get extracted from previous zipFile
     * @param fileNameToSearchFor search for specific name
     * @return {@link List} of Strings for each line in file {@code fileNameToSearchFor}
     */
    public static List<String> extractLinesFromRepoFile(List<File> filesFromZipFile, String fileNameToSearchFor) {
        if(filesFromZipFile.size() < 1 && fileNameToSearchFor != null) {
            throw new IllegalArgumentException();
        }
        List<String> lines = null;
        for (File file : filesFromZipFile) {
            if (file.getName().equalsIgnoreCase(fileNameToSearchFor)) {
                try {
                    FileInputStream fis = new FileInputStream(file);
                    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                    lines = br.lines().collect(Collectors.toList());
                    br.close();
                    if (file.exists())
                        file.delete();
                } catch (IOException ignored) { }
            }
        }
        return lines;
    }
}
