import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
import java.util.Scanner;

public class Client {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        try {
            System.out.print("Введите IP-адрес сервера (например, localhost): ");
            String serverIp = scanner.nextLine();
            System.out.print("Введите порт сервера (например, 8080): ");
            String port = scanner.nextLine();

            String serverUrl = "http://" + serverIp + ":" + port + "/api/matrix/sort";

            System.out.print("Введите количество потоков: ");
            int threadCount = scanner.nextInt();
            System.out.print("Введите количество строк матрицы: ");
            int rows = scanner.nextInt();
            System.out.print("Введите количество столбцов матрицы: ");
            int cols = scanner.nextInt();

            for (int i = 0; i < threadCount; i++) {
                int threadId = i + 1;
                new Thread(() -> {
                    try {
                        int[][] matrix = generateRandomMatrix(rows, cols);
                        String jsonInputString = buildMatrixJson(matrix);

                        System.out.println("Поток " + threadId + " отправляет матрицу...");
                        sendMatrixToServer(serverUrl, jsonInputString, rows, cols, threadId);

                    } catch (Exception e) {
                        System.err.println("Ошибка в потоке " + threadId);
                        e.printStackTrace();
                    }
                }).start();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            scanner.close();
        }
    }

    private static int[][] generateRandomMatrix(int rows, int cols) {
        Random random = new Random();
        int[][] matrix = new int[rows][cols];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                matrix[i][j] = random.nextInt(100);
            }
        }
        return matrix;
    }

    private static String buildMatrixJson(int[][] matrix) {
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("{ \"matrix\": [");

        for (int i = 0; i < matrix.length; i++) {
            jsonBuilder.append("[");
            for (int j = 0; j < matrix[i].length; j++) {
                jsonBuilder.append(matrix[i][j]);
                if (j < matrix[i].length - 1) jsonBuilder.append(", ");
            }
            jsonBuilder.append("]");
            if (i < matrix.length - 1) jsonBuilder.append(", ");
        }

        jsonBuilder.append("] }");
        return jsonBuilder.toString();
    }

    private static void sendMatrixToServer(String serverUrl, String jsonInputString, int rows, int cols, int threadId) {
        try {
            URL url = new URL(serverUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }

                System.out.println("Поток " + threadId + " получил ответ от сервера:");
                printPartialMatrix(response.toString(), rows, cols);

            }

            connection.disconnect();

        } catch (Exception e) {
            System.err.println("Ошибка в потоке " + threadId);
            e.printStackTrace();
        }
    }

    private static void printPartialMatrix(String response, int rows, int cols) {
        System.out.println("Ответ сервера (первые 10 строк и столбцов):");

        String[] rowStrings = response.split("],\\[");
        for (int i = 0; i < Math.min(10, rowStrings.length); i++) {
            String[] elements = rowStrings[i].replaceAll("[^0-9,]", "").split(",");

            for (int j = 0; j < Math.min(10, elements.length); j++) {
                System.out.printf("%4s", elements[j]);
            }
            System.out.println();
        }
    }
}
