package com.example.service;

import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class MatrixService {
    private static final Logger logger = LoggerFactory.getLogger(MatrixService.class);
    private final ExecutorService executor = Executors.newCachedThreadPool();

    public CompletableFuture<int[][]> sortColumnsByFirstElementAsync(int[][] matrix) {
        logger.info("Начало асинхронной сортировки в потоке: " + Thread.currentThread().getName());

        return CompletableFuture.supplyAsync(() -> {
            logger.info("Сортировка выполняется в потоке: " + Thread.currentThread().getName());
            return sortColumnsByFirstElement(matrix);
        }, executor);
    }

    private int[][] sortColumnsByFirstElement(int[][] matrix) {
        int cols = matrix[0].length;
        int rows = matrix.length;
        Integer[] indices = new Integer[cols];

        for (int i = 0; i < cols; i++) indices[i] = i;

        Arrays.sort(indices, (a, b) -> Integer.compare(matrix[0][a], matrix[0][b]));

        int[][] sortedMatrix = new int[rows][cols];
        for (int i = 0; i < cols; i++) {
            for (int j = 0; j < rows; j++) {
                sortedMatrix[j][i] = matrix[j][indices[i]];
            }
        }
        logger.info("Сортировка завершена в потоке: " + Thread.currentThread().getName());
        return sortedMatrix;
    }
}