/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

package org.elasticsearch.action.admin.cluster.tasks;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.master.TransportMasterNodeReadAction;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.cluster.service.PendingClusterTask;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;

import java.util.List;

public class TransportPendingClusterTasksAction extends TransportMasterNodeReadAction<
    PendingClusterTasksRequest,
    PendingClusterTasksResponse> {

    private static final Logger logger = LogManager.getLogger(TransportPendingClusterTasksAction.class);

    private final ClusterService clusterService;

    @Inject
    public TransportPendingClusterTasksAction(
        TransportService transportService,
        ClusterService clusterService,
        ThreadPool threadPool,
        ActionFilters actionFilters,
        IndexNameExpressionResolver indexNameExpressionResolver
    ) {
        super(
            PendingClusterTasksAction.NAME,
            transportService,
            clusterService,
            threadPool,
            actionFilters,
            PendingClusterTasksRequest::new,
            indexNameExpressionResolver,
            PendingClusterTasksResponse::new,
            ThreadPool.Names.SAME
        );
        this.clusterService = clusterService;
    }

    @Override
    protected ClusterBlockException checkBlock(PendingClusterTasksRequest request, ClusterState state) {
        return null;
    }

    @Override
    protected void masterOperation(
        Task task,
        PendingClusterTasksRequest request,
        ClusterState state,
        ActionListener<PendingClusterTasksResponse> listener
    ) {
        logger.trace("fetching pending tasks from cluster service");
        final List<PendingClusterTask> pendingTasks = clusterService.getMasterService().pendingTasks();
        logger.trace("done fetching pending tasks from cluster service");
        listener.onResponse(new PendingClusterTasksResponse(pendingTasks));
    }
}
