import java.io.*;

public class Main {
    public static void main(String[] args) throws Exception {
        if (args.length != 2) {
            System.out.println("Usage: java MatrixSorter <rows> <columns>");
            return;
        }

        int rows = Integer.parseInt(args[0]);
        int cols = Integer.parseInt(args[1]);

        int[][] matrix = MatrixUtils.generateMatrix(rows, cols);
        int[][] matrixCopy1 = MatrixUtils.copyMatrix(matrix);
        int[][] matrixCopy2 = MatrixUtils.copyMatrix(matrix);

        BufferedWriter writer = new BufferedWriter(new FileWriter("matrix_output.txt"));

        writer.write("Original Matrix:\n");
        MatrixUtils.printMatrixToFile(matrix, writer);

        System.out.println("Initial Matrix (first 10 elements):");
        MatrixUtils.printMatrix(matrix);

        long startTime, endTime;

        // Single-threaded
        startTime = System.currentTimeMillis();
        SingleThreadSorter.sortColumns(matrix);
        endTime = System.currentTimeMillis();
        System.out.println("\nSingle-threaded (first 10 elements):");
        MatrixUtils.printMatrix(matrix);
        writer.write("\nSingle-threaded:\n");
        MatrixUtils.printMatrixToFile(matrix, writer);
        writer.write("Single-threaded time: " + (endTime - startTime) + "ms\n");
        System.out.println("Single-threaded time: " + (endTime - startTime) + "ms\n");

        // ThreadPoolExecutor
        startTime = System.currentTimeMillis();
        ThreadPoolSorter.sort(matrixCopy1);
        endTime = System.currentTimeMillis();
        System.out.println("\nThreadPoolExecutor (first 10 elements):");
        MatrixUtils.printMatrix(matrixCopy1);
        writer.write("\nThreadPoolExecutor:\n");
        MatrixUtils.printMatrixToFile(matrixCopy1, writer);
        writer.write("ThreadPoolExecutor time: " + (endTime - startTime) + "ms\n");
        System.out.println("ThreadPoolExecutor time: " + (endTime - startTime) + "ms\n");

        // ForkJoinPool
        startTime = System.currentTimeMillis();
        ForkJoinSorter.sort(matrixCopy2);
        endTime = System.currentTimeMillis();
        System.out.println("\nForkJoinPool (first 10 elements):");
        MatrixUtils.printMatrix(matrixCopy2);
        writer.write("\nSorted Matrix (ForkJoinPool):\n");
        MatrixUtils.printMatrixToFile(matrixCopy2, writer);
        writer.write("ForkJoinPool time: " + (endTime - startTime) + "ms");
        System.out.println("ForkJoinPool time: " + (endTime - startTime) + "ms");

        writer.close();
    }
}