package ru.kuznec;

import org.apache.ignite.IgniteException;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.compute.ComputeJob;
import org.apache.ignite.compute.ComputeJobResult;
import org.apache.ignite.compute.ComputeJobResultPolicy;
import org.apache.ignite.compute.ComputeTask;
import org.apache.ignite.compute.ComputeTaskName;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@ComputeTaskName("MatrixMinTaskUser")
public class MatrixMinTask implements ComputeTask<Void, Integer> {
    private final int[][] matrix;
    private final int startRow;
    private final int endRow;

    public MatrixMinTask(int[][] matrix, int startRow, int endRow) {
        this.matrix = matrix;
        this.startRow = startRow;
        this.endRow = endRow;
    }

    @Override
    public Map<? extends ComputeJob, ClusterNode> map(List<ClusterNode> subgrid, Void arg) throws IgniteException {
        ComputeJob job = new MatrixMinJob(matrix, startRow, endRow);
        return Collections.singletonMap(job, subgrid.get(0));
    }

    @Override
    public ComputeJobResultPolicy result(ComputeJobResult res, List<ComputeJobResult> received) throws IgniteException {
        return ComputeJobResultPolicy.WAIT;
    }

    @Override
    public Integer reduce(List<ComputeJobResult> results) throws IgniteException {
        int globalMin = Integer.MAX_VALUE;
        for (ComputeJobResult res : results) {
            globalMin = Math.min(globalMin, res.getData());
        }
        return globalMin;
    }
}
