package enea.lecservice.utils;

import lombok.extern.log4j.Log4j2;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

@Log4j2
public class FileUtils {
    public static boolean exists(String fileName) {
        try {
            File file = ResourceUtils.getFile("classpath:" + fileName);
            return file.exists();
        }
        catch (IOException e) {
            log.warn("File name {} with data was not found", fileName);
            return false;
        }
    }

    public static String getContentAsString(String fileName, String path) {
        if (path != null && !path.isBlank()) {
            try {
                File file = new File(fileName);
                if (file.exists()) {
                    return new String(Files.readAllBytes(file.toPath()));
                }
            }
            catch (Exception ex) {
                log.error("External file {} on path {} is not found!", fileName, path);
            }
        }
        else {
            return getContentAsString(fileName);
        }
        return  null;
    }

    public static String getContentAsString(String fileName) {
        try {
            File file = ResourceUtils.getFile("classpath:" + fileName);
            return new String(Files.readAllBytes(file.toPath()));
        }
        catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
}
