package org.opentest4j.reporting.tooling.spi.htmlreport;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * Immutable implementation of {@link Subsections}.
 * <p>
 * Use the builder to create immutable instances:
 * {@code new Subsections.Builder()}.
 */
@SuppressWarnings({"all"})
final class ImmutableSubsections implements Subsections {
  private final List<Section> content;

  private ImmutableSubsections(List<Section> content) {
    this.content = content;
  }

  /**
   * @return The value of the {@code content} attribute
   */
  @Override
  public List<Section> getContent() {
    return content;
  }

  /**
   * Copy the current immutable object with elements that replace the content of {@link Subsections#getContent() content}.
   * @param elements The elements to set
   * @return A modified copy of {@code this} object
   */
  public final ImmutableSubsections withContent(Section... elements) {
    List<Section> newValue = createUnmodifiableList(false, createSafeList(Arrays.asList(elements), true, false));
    return new ImmutableSubsections(newValue);
  }

  /**
   * Copy the current immutable object with elements that replace the content of {@link Subsections#getContent() content}.
   * A shallow reference equality check is used to prevent copying of the same value by returning {@code this}.
   * @param elements An iterable of content elements to set
   * @return A modified copy or {@code this} if not changed
   */
  public final ImmutableSubsections withContent(Iterable<? extends Section> elements) {
    if (this.content == elements) return this;
    List<Section> newValue = createUnmodifiableList(false, createSafeList(elements, true, false));
    return new ImmutableSubsections(newValue);
  }

  /**
   * This instance is equal to all instances of {@code ImmutableSubsections} that have equal attribute values.
   * @return {@code true} if {@code this} is equal to {@code another} instance
   */
  @Override
  public boolean equals(Object another) {
    if (this == another) return true;
    return another instanceof ImmutableSubsections
        && equalsByValue((ImmutableSubsections) another);
  }

  private boolean equalsByValue(ImmutableSubsections another) {
    return content.equals(another.content);
  }

  /**
   * Computes a hash code from attributes: {@code content}.
   * @return hashCode value
   */
  @Override
  public int hashCode() {
    int h = 5381;
    h += (h << 5) + content.hashCode();
    return h;
  }

  /**
   * Prints the immutable value {@code Subsections} with attribute values.
   * @return A string representation of the value
   */
  @Override
  public String toString() {
    return "Subsections{"
        + "content=" + content
        + "}";
  }

  /**
   * Creates an immutable copy of a {@link Subsections} value.
   * Uses accessors to get values to initialize the new immutable instance.
   * If an instance is already immutable, it is returned as is.
   * @param instance The instance to copy
   * @return A copied immutable Subsections instance
   */
  public static Subsections copyOf(Subsections instance) {
    if (instance instanceof ImmutableSubsections) {
      return (ImmutableSubsections) instance;
    }
    return new Subsections.Builder()
        .addAllContent(instance.getContent())
        .build();
  }

  /**
   * Builds instances of type {@link Subsections Subsections}.
   * Initialize attributes and then invoke the {@link #build()} method to create an
   * immutable instance.
   * <p><em>{@code Builder} is not thread-safe and generally should not be stored in a field or collection,
   * but instead used immediately to create instances.</em>
   */
  public static class Builder {
    private List<Section> content = new ArrayList<Section>();

    /**
     * Creates a builder for {@link Subsections Subsections} instances.
     * <pre>
     * new Subsections.Builder()
     *    .addContent|addAllContent(org.opentest4j.reporting.tooling.spi.htmlreport.Section) // {@link Subsections#getContent() content} elements
     *    .build();
     * </pre>
     */
    public Builder() {
      if (!(this instanceof Subsections.Builder)) {
        throw new UnsupportedOperationException("Use: new Subsections.Builder()");
      }
    }

    /**
     * Adds one element to {@link Subsections#getContent() content} list.
     * @param element A content element
     * @return {@code this} builder for use in a chained invocation
     */
    public final Subsections.Builder addContent(Section element) {
      this.content.add(Objects.requireNonNull(element, "content element"));
      return (Subsections.Builder) this;
    }

    /**
     * Adds elements to {@link Subsections#getContent() content} list.
     * @param elements An array of content elements
     * @return {@code this} builder for use in a chained invocation
     */
    public final Subsections.Builder addContent(Section... elements) {
      for (Section element : elements) {
        this.content.add(Objects.requireNonNull(element, "content element"));
      }
      return (Subsections.Builder) this;
    }


    /**
     * Sets or replaces all elements for {@link Subsections#getContent() content} list.
     * @param elements An iterable of content elements
     * @return {@code this} builder for use in a chained invocation
     */
    public final Subsections.Builder content(Iterable<? extends Section> elements) {
      this.content.clear();
      return addAllContent(elements);
    }

    /**
     * Adds elements to {@link Subsections#getContent() content} list.
     * @param elements An iterable of content elements
     * @return {@code this} builder for use in a chained invocation
     */
    public final Subsections.Builder addAllContent(Iterable<? extends Section> elements) {
      for (Section element : elements) {
        this.content.add(Objects.requireNonNull(element, "content element"));
      }
      return (Subsections.Builder) this;
    }

    /**
     * Builds a new {@link Subsections Subsections}.
     * @return An immutable instance of Subsections
     * @throws java.lang.IllegalStateException if any required attributes are missing
     */
    public Subsections build() {
      return new ImmutableSubsections(createUnmodifiableList(true, content));
    }
  }

  private static <T> List<T> createSafeList(Iterable<? extends T> iterable, boolean checkNulls, boolean skipNulls) {
    ArrayList<T> list;
    if (iterable instanceof Collection<?>) {
      int size = ((Collection<?>) iterable).size();
      if (size == 0) return Collections.emptyList();
      list = new ArrayList<>(size);
    } else {
      list = new ArrayList<>();
    }
    for (T element : iterable) {
      if (skipNulls && element == null) continue;
      if (checkNulls) Objects.requireNonNull(element, "element");
      list.add(element);
    }
    return list;
  }

  private static <T> List<T> createUnmodifiableList(boolean clone, List<? extends T> list) {
    switch(list.size()) {
    case 0: return Collections.emptyList();
    case 1: return Collections.singletonList(list.get(0));
    default:
      if (clone) {
        return Collections.unmodifiableList(new ArrayList<>(list));
      } else {
        if (list instanceof ArrayList<?>) {
          ((ArrayList<?>) list).trimToSize();
        }
        return Collections.unmodifiableList(list);
      }
    }
  }
}
