package com.codegym.task.task31.task3101;

/*
Iterating through a file tree

*/

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;


public class Solution {
    public static void main(String[] args) {
        String path = args[0];
        String resultFileAbsolutePath = args[1];
        TreeMap<String, byte[]> tree = new TreeMap<>(String::compareTo);
        File file = new File(path);
        generateTree(file, tree);
        try {
            File resultFile = new File(resultFileAbsolutePath);
            File newResultFile = new File(resultFile.getParentFile() + "/allFilesContent.txt");
            if (FileUtils.isExist(newResultFile)) {  FileUtils.deleteFile(newResultFile); }
            FileUtils.renameFile(resultFile, newResultFile);
            FileUtils.renameFile(resultFile, newResultFile);
            try (FileOutputStream fileOutputStream = new FileOutputStream(newResultFile)) {
                for (byte[] bytes : tree.values()) {
                    fileOutputStream.write(bytes);
                    fileOutputStream.write("\n".getBytes());
                }
            }
        } catch (IOException ignored) {}
    }

    public static void generateTree(File root, TreeMap tree) {
        Arrays.stream(Objects.requireNonNull(root.listFiles())).forEach(file -> {
            if (file.isDirectory()) { generateTree(file, tree); }
            else if (file.length() < 51) {
                try { tree.put(file.getName(), Files.readAllBytes(Paths.get(file.getPath()))); }
                catch (IOException ignored) {}
            }
        });
    }
}