/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.execution.scheduler;

import com.facebook.presto.execution.StageExecutionState;
import com.google.common.collect.ImmutableList;

import javax.annotation.concurrent.GuardedBy;

import java.util.List;

import static com.facebook.presto.execution.StageExecutionState.PLANNED;
import static java.util.Objects.requireNonNull;

public class SectionExecution
{
    private final StageExecutionAndScheduler rootStage;
    private final List<StageExecutionAndScheduler> allStages;

    @GuardedBy("this")
    private volatile boolean aborted;

    public SectionExecution(StageExecutionAndScheduler rootStage, List<StageExecutionAndScheduler> allStages)
    {
        this.rootStage = requireNonNull(rootStage, "rootStage is null");
        this.allStages = ImmutableList.copyOf(requireNonNull(allStages, "allStages is null"));
    }

    public StageExecutionAndScheduler getRootStage()
    {
        return rootStage;
    }

    public List<StageExecutionAndScheduler> getSectionStages()
    {
        return allStages;
    }

    public boolean isFinished()
    {
        StageExecutionState rootStageState = rootStage.getStageExecution().getState();
        return rootStageState.isDone() && !rootStageState.isFailure();
    }

    public boolean isFailed()
    {
        StageExecutionState rootStageState = rootStage.getStageExecution().getState();
        return rootStageState.isFailure();
    }

    public boolean isRunning()
    {
        StageExecutionState rootStageState = rootStage.getStageExecution().getState();
        return !rootStageState.isDone() && rootStageState != PLANNED;
    }

    public synchronized boolean abort()
    {
        if (!aborted) {
            aborted = true;
            for (StageExecutionAndScheduler stageExecutionAndScheduler : allStages) {
                stageExecutionAndScheduler.getStageExecution().abort();
                stageExecutionAndScheduler.getStageScheduler().close();
            }
            return true;
        }
        return false;
    }
}
