/*
 * 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;

import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.planner.PlanFragment;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableList;

import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;

import java.net.URI;
import java.util.List;
import java.util.Optional;

import static com.google.common.base.MoreObjects.toStringHelper;
import static java.util.Objects.requireNonNull;

@Immutable
public class StageInfo
{
    private final StageId stageId;
    private final StageState state;
    private final URI self;
    private final PlanFragment plan;
    private final List<Type> types;
    private final StageStats stageStats;
    private final List<TaskInfo> tasks;
    private final List<StageInfo> subStages;
    private final ExecutionFailureInfo failureCause;

    @JsonCreator
    public StageInfo(
            @JsonProperty("stageId") StageId stageId,
            @JsonProperty("state") StageState state,
            @JsonProperty("self") URI self,
            @JsonProperty("plan") @Nullable PlanFragment plan,
            @JsonProperty("types") List<Type> types,
            @JsonProperty("stageStats") StageStats stageStats,
            @JsonProperty("tasks") List<TaskInfo> tasks,
            @JsonProperty("subStages") List<StageInfo> subStages,
            @JsonProperty("failureCause") ExecutionFailureInfo failureCause)
    {
        requireNonNull(stageId, "stageId is null");
        requireNonNull(state, "state is null");
        requireNonNull(self, "self is null");
        requireNonNull(stageStats, "stageStats is null");
        requireNonNull(tasks, "tasks is null");
        requireNonNull(subStages, "subStages is null");

        this.stageId = stageId;
        this.state = state;
        this.self = self;
        this.plan = plan;
        this.types = types;
        this.stageStats = stageStats;
        this.tasks = ImmutableList.copyOf(tasks);
        this.subStages = subStages;
        this.failureCause = failureCause;
    }

    @JsonProperty
    public StageId getStageId()
    {
        return stageId;
    }

    @JsonProperty
    public StageState getState()
    {
        return state;
    }

    @JsonProperty
    public URI getSelf()
    {
        return self;
    }

    @JsonProperty
    @Nullable
    public PlanFragment getPlan()
    {
        return plan;
    }

    @JsonProperty
    public List<Type> getTypes()
    {
        return types;
    }

    @JsonProperty
    public StageStats getStageStats()
    {
        return stageStats;
    }

    @JsonProperty
    public List<TaskInfo> getTasks()
    {
        return tasks;
    }

    @JsonProperty
    public List<StageInfo> getSubStages()
    {
        return subStages;
    }

    @JsonProperty
    public ExecutionFailureInfo getFailureCause()
    {
        return failureCause;
    }

    public boolean isFinalStageInfo()
    {
        return state.isDone() && tasks.stream().allMatch(taskInfo -> taskInfo.getTaskStatus().getState().isDone());
    }

    @Override
    public String toString()
    {
        return toStringHelper(this)
                .add("stageId", stageId)
                .add("state", state)
                .toString();
    }

    public static List<StageInfo> getAllStages(Optional<StageInfo> stageInfo)
    {
        ImmutableList.Builder<StageInfo> collector = ImmutableList.builder();
        addAllStages(stageInfo, collector);
        return collector.build();
    }

    private static void addAllStages(Optional<StageInfo> stageInfo, ImmutableList.Builder<StageInfo> collector)
    {
        stageInfo.ifPresent(stage -> {
            collector.add(stage);
            stage.getSubStages().stream()
                    .forEach(subStage -> addAllStages(Optional.ofNullable(subStage), collector));
        });
    }
}

@@ -1064,16 +1064,73 @@
 Helper;%0A
+import static com.google.common.graph.Traverser.forTree;%0A
 import s
@@ -3963,23 +3963,16 @@
  public 
-static 
 List%3CSta
@@ -3996,37 +3996,8 @@
 ges(
-Optional%3CStageInfo%3E stageInfo
 )%0A  
@@ -4008,16 +4008,23 @@
         
+return 
 Immutabl
@@ -4033,139 +4033,72 @@
 ist.
-Builder%3CStageInfo%3E collector = ImmutableList.builder();%0A        addAllStages(stageInfo, collector);%0A        return collector.build(
+copyOf(forTree(StageInfo::getSubStages).depthFirstPreOrder(this)
 );%0A 
@@ -4112,22 +4112,21 @@
    p
-rivate
+ublic
  static 
 void
@@ -4125,16 +4125,27 @@
 tic 
-void add
+List%3CStageInfo%3E get
 AllS
@@ -4183,282 +4183,95 @@
 Info
-, ImmutableList.Builder%3CStageInfo%3E collector)%0A    %7B%0A        stageInfo.ifPresent(stage -%3E %7B%0A            collector.add(stage);%0A            stage.getSub
+)%0A    %7B%0A        return stageInfo.map(StageInfo::getAll
 Stages
-(
 ).
-stream()%0A                    .forEach(subStage -%3E addAllStages(Optional.ofNullable(subStage), collector));%0A        %7D
+orElse(ImmutableList.of()
 );%0A 

Simplify StageInfo#getAllStages