/*
 * Copyright (c) 2017-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

package com.facebook.litho.sections;

import static android.support.v4.util.Pools.SynchronizedPool;

import android.support.annotation.VisibleForTesting;
import android.support.v4.util.Pools.Pool;
import com.facebook.litho.sections.annotations.GroupSectionSpec;
import java.util.ArrayList;
import java.util.List;

/**
 * Utility class that represents the children of a {@link GroupSectionSpec}. This is used to mimic
 * litho's usage of the Container class in {@link com.facebook.litho.annotations.LayoutSpec}'s API
 */
public class Children {

  private static final Pool<Builder> sBuildersPool = new SynchronizedPool<>(2);

  private List<Section> mSections;

  private Children() {
    mSections = new ArrayList<>();
  }

  public static Builder create() {
    Builder builder = sBuildersPool.acquire();
    if (builder == null) {
      builder = new Builder();
    }
    builder.init(new Children());

    return builder;
  }

  @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE)
  public List<Section> getChildren() {
    return mSections;
  }

  public static class Builder {

    private Children mChildren;

    private Builder() {

    }

    private void init(Children children) {
      mChildren = children;
    }

    public Builder child(Section<?> section) {
      if (section != null) {
        mChildren.mSections.add(section);
      }

      return this;
    }

    public Builder child(Section.Builder<?, ?> sectionBuilder) {
      if (sectionBuilder != null) {
        mChildren.mSections.add(sectionBuilder.build());
      }

      return this;
    }

    public Children build() {
      Children children = mChildren;
      mChildren = null;
      sBuildersPool.release(this);

      return children;
    }
  }
}

@@ -1460,16 +1460,10 @@
 () %7B
-%0A%0A    
 %7D%0A
+
 %0A   
@@ -1580,24 +1580,51 @@
  section) %7B%0A
+      verifyValidState();%0A%0A
       if (se
@@ -1778,24 +1778,51 @@
 nBuilder) %7B%0A
+      verifyValidState();%0A%0A
       if (se
@@ -1963,24 +1963,51 @@
 n build() %7B%0A
+      verifyValidState();%0A%0A
       Childr
@@ -2087,24 +2087,24 @@
 ase(this);%0A%0A
-
       return
@@ -2119,15 +2119,196 @@
 n;%0A    %7D
+%0A%0A    private void verifyValidState() %7B%0A      if (mChildren == null) %7B%0A        throw new IllegalStateException(%22.build() call has been already made on this Builder.%22);%0A      %7D%0A    %7D
 %0A  %7D%0A%7D%0A

Throw when Children.Builder's methods are accessed after its build() method is called