package nothingness;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

public class MeaningGenerator {

	static String SEED = "nada exist";
	static String KEY = "abaddon";
	static String EXIT = "error exist";

	public MeaningGenerator(String abyss, String rake) {
		boolean void0 = true;
		while (void0) {
			try {
				Map<Character, List<String>> cry = capturingChaos(abyss, rake);
				for (char symbol : rake.toCharArray()) {
					if (symbol == ' ') {
						System.out.println();
					} else {
						String howl = getRandomNoise(cry, symbol);
						while (howl.length() < 4) {
							howl = getRandomNoise(cry, symbol);
						}
						if (howl.trim().equalsIgnoreCase(KEY)) {
							throw new Exception();
						} else {
							System.out.println(howl);
						}
					}
				}
				System.out.println("\n" + "*" + "\n");
			} catch (Exception e) {
				System.out.println("\n" + "#" + "\n");
				System.out.println(EXIT);
				void0 = false;
			}
		}
	}

	private Map<Character, List<String>> capturingChaos(String abyss, String rake) throws IOException {
		Map<Character, List<String>> cry = new HashMap<>();
		for (char c : rake.toCharArray()) {
			cry.put(Character.toLowerCase(c), new ArrayList<>());
		}

		for (String line : Files.readAllLines(Path.of(abyss))) {
			if (!line.isEmpty()) {
				String[] chaos = line.replaceAll("[^\\p{L}\\s]", " ").split("[^\\p{L}]+");
				for (String fragmentOfChaos : chaos) {
					if (!fragmentOfChaos.isEmpty()) {
						char theOne = Character.toLowerCase(fragmentOfChaos.charAt(0));
						List<String> symbols = cry.get(theOne);
						if (symbols != null) {
							cry.get(theOne).add(fragmentOfChaos);
						}
					}
				}
			}
		}
		return cry;
	}

	private String getRandomNoise(Map<Character, List<String>> chaos, char symbol) {
		List<String> list = chaos.get(Character.toLowerCase(symbol));
		String noise = list.get(ThreadLocalRandom.current().nextInt(list.size()));
		noise = Character.toUpperCase(noise.charAt(0)) + noise.substring(1).toLowerCase();
		return noise;
	}

	public static void main(String[] args) {
		new MeaningGenerator("/void/uchronécroses_V7-final_draft-3.txt", SEED);
	}

}