package ua.nure.jfn.task4;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Part4 {

	private static final Path INPUT_FILE = Paths.get("part4.txt");
	private static final Path OUTPUT_FILE = Paths.get("part4_sorted.txt");

	private static final int NUM_INTEGERS = 10;
	private static final int MAX_VALUE = 50;

	public static void main(String[] args) {
		List<Integer> nums;

		if (!Files.exists(INPUT_FILE)) {
			Random random = new Random();

			nums = new ArrayList<Integer>(NUM_INTEGERS);
			for (int i = 0; i < NUM_INTEGERS; i++) {
				nums.add(random.nextInt(MAX_VALUE + 1));
			}

			if (!tryWriteNums(INPUT_FILE, nums)) {
				return;
			}
		}

		nums = tryReadNums(INPUT_FILE);
		if (nums == null) {
			return;
		}

		System.out.printf("input ==> %s\n", joinInts(nums));

		nums = sortDedup(nums);
		if (!tryWriteNums(OUTPUT_FILE, nums)) {
			return;
		}

		System.out.printf("output ==> %s\n", joinInts(nums));
	}

	private static List<Integer> sortDedup(List<Integer> nums) {
		for (int i = 0; i < nums.size() - 1; i++) {
			for (int j = 0; j < nums.size() - i - 1; j++) {
				int a = nums.get(j);
				int b = nums.get(j + 1);

				if (a > b) {
					nums.set(j, b);
					nums.set(j + 1, a);
				}
			}
		}

		List<Integer> dedup = new ArrayList<Integer>();
		for (int num : nums) {
			if (dedup.indexOf(num) == -1)
				dedup.add(num);
		}

		return dedup;
	}

	private static boolean tryWriteNums(Path path, List<Integer> nums) {
		try {
			String s = "";
			for (int i = 0; i < nums.size(); i++) {
				s += " " + nums.get(i);
			}

			Files.write(path, s.trim().getBytes(StandardCharsets.UTF_8));
		} catch (IOException e) {
			return false;
		}

		return true;
	}

	private static List<Integer> tryReadNums(Path path) {
		List<Integer> nums = new ArrayList<Integer>(NUM_INTEGERS);
		try {
			String content = Files.readString(path);
			for (String s : content.trim().split(" ")) {
				nums.add(Integer.parseInt(s));
			}
		} catch (Exception e) {
			return null;
		}

		return nums;
	}

	private static String joinInts(Iterable<Integer> numbers) {
		String result = "";
		for (int num : numbers) {
			result += " " + num;
		}

		return result.trim();
	}
}
