package ru.second;

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

import static java.util.Objects.isNull;

public class Main {

    public static final String INPUT_PATH = System.getenv("INPUT_PATH");
    public static final String INPUT_FILE_NAME = "data.txt";

    public static final String OUTPUT_PATH = System.getenv("OUTPUT_PATH");
    public static final String RESULT_FILE_NAME = "result.txt";

    public static void main(String[] args) {
        if (isNull(INPUT_PATH) || INPUT_PATH.isEmpty() || isNull(OUTPUT_PATH) || OUTPUT_PATH.isEmpty()) {
            System.out.printf("Отсутствуют переменные окружения INPUT_PATH = '%s' или OUTPUT_PATH = '%s'%n",
                    INPUT_PATH, OUTPUT_PATH);
            return;
        }

        var inputFile = new File(INPUT_PATH + File.separator + INPUT_FILE_NAME);
        if (!inputFile.exists()) {
            System.out.println("Входной файл не существует");
            return;
        }

        try (var stream = Files.lines(inputFile.toPath());
             var writer = new FileWriter(OUTPUT_PATH + File.separator + RESULT_FILE_NAME);
        ) {
            var min = stream.map(Main::parseInt).reduce(Integer::min);
            if (min.isEmpty()) {
                System.out.println("Не найдено минимальное значение среди строк файла");
                return;
            }
            var minValue = Math.pow(min.get(), 3);
            System.out.printf("Get min value = '%d'%n", min.get());
            writer.append(Double.toString(minValue));
            System.out.printf("To file %s was written value %f%n", RESULT_FILE_NAME, minValue);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

    private static Integer parseInt(String line) {
        line = line.replace("\\n", "");
        return Integer.parseInt(line);
    }
}