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

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Immutable implementation of {@link KeyValuePairs}.
 * <p>
 * Use the builder to create immutable instances:
 * {@code new KeyValuePairs.Builder()}.
 */
@SuppressWarnings({"all"})
final class ImmutableKeyValuePairs
    implements KeyValuePairs {
  private final Map<String, String> content;

  private ImmutableKeyValuePairs(Map<String, String> content) {
    this.content = content;
  }

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

  /**
   * Copy the current immutable object by replacing the {@link KeyValuePairs#getContent() content} map with the specified map.
   * Nulls are not permitted as keys or values.
   * A shallow reference equality check is used to prevent copying of the same value by returning {@code this}.
   * @param entries The entries to replace the content map
   * @return A modified copy or {@code this} if not changed
   */
  public final ImmutableKeyValuePairs withContent(Map<String, ? extends String> entries) {
    if (this.content == entries) return this;
    Map<String, String> newValue = createUnmodifiableMap(true, false, entries);
    return new ImmutableKeyValuePairs(newValue);
  }

  /**
   * This instance is equal to all instances of {@code ImmutableKeyValuePairs} 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 ImmutableKeyValuePairs
        && equalsByValue((ImmutableKeyValuePairs) another);
  }

  private boolean equalsByValue(ImmutableKeyValuePairs 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 KeyValuePairs} with attribute values.
   * @return A string representation of the value
   */
  @Override
  public String toString() {
    return "KeyValuePairs{"
        + "content=" + content
        + "}";
  }

  /**
   * Creates an immutable copy of a {@link KeyValuePairs} 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 KeyValuePairs instance
   */
  public static KeyValuePairs copyOf(KeyValuePairs instance) {
    if (instance instanceof ImmutableKeyValuePairs) {
      return (ImmutableKeyValuePairs) instance;
    }
    return new KeyValuePairs.Builder()
        .putAllContent(instance.getContent())
        .build();
  }

  /**
   * Builds instances of type {@link KeyValuePairs KeyValuePairs}.
   * 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 Map<String, String> content = new LinkedHashMap<String, String>();

    /**
     * Creates a builder for {@link KeyValuePairs KeyValuePairs} instances.
     * <pre>
     * new KeyValuePairs.Builder()
     *    .putContent|putAllContent(String =&gt; String) // {@link KeyValuePairs#getContent() content} mappings
     *    .build();
     * </pre>
     */
    public Builder() {
      if (!(this instanceof KeyValuePairs.Builder)) {
        throw new UnsupportedOperationException("Use: new KeyValuePairs.Builder()");
      }
    }

    /**
     * Put one entry to the {@link KeyValuePairs#getContent() content} map.
     * @param key The key in the content map
     * @param value The associated value in the content map
     * @return {@code this} builder for use in a chained invocation
     */
    public final KeyValuePairs.Builder putContent(String key, String value) {
      this.content.put(
          Objects.requireNonNull(key, "content key"),
          Objects.requireNonNull(value, value == null ? "content value for key: " + key : null));
      return (KeyValuePairs.Builder) this;
    }

    /**
     * Put one entry to the {@link KeyValuePairs#getContent() content} map. Nulls are not permitted
     * @param entry The key and value entry
     * @return {@code this} builder for use in a chained invocation
     */
    public final KeyValuePairs.Builder putContent(Map.Entry<String, ? extends String> entry) {
      String k = entry.getKey();
      String v = entry.getValue();
      this.content.put(
          Objects.requireNonNull(k, "content key"),
          Objects.requireNonNull(v, v == null ? "content value for key: " + k : null));
      return (KeyValuePairs.Builder) this;
    }

    /**
     * Sets or replaces all mappings from the specified map as entries for the {@link KeyValuePairs#getContent() content} map. Nulls are not permitted
     * @param entries The entries that will be added to the content map
     * @return {@code this} builder for use in a chained invocation
     */
    public final KeyValuePairs.Builder content(Map<String, ? extends String> entries) {
      this.content.clear();
      return putAllContent(entries);
    }

    /**
     * Put all mappings from the specified map as entries to {@link KeyValuePairs#getContent() content} map. Nulls are not permitted
     * @param entries The entries that will be added to the content map
     * @return {@code this} builder for use in a chained invocation
     */
    public final KeyValuePairs.Builder putAllContent(Map<String, ? extends String> entries) {
      for (Map.Entry<String, ? extends String> e : entries.entrySet()) {
        String k = e.getKey();
        String v = e.getValue();
        this.content.put(
            Objects.requireNonNull(k, "content key"),
            Objects.requireNonNull(v, v == null ? "content value for key: " + k : null));
      }
      return (KeyValuePairs.Builder) this;
    }

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

  private static <K, V> Map<K, V> createUnmodifiableMap(boolean checkNulls, boolean skipNulls, Map<? extends K, ? extends V> map) {
    switch (map.size()) {
    case 0: return Collections.emptyMap();
    case 1: {
      Map.Entry<? extends K, ? extends V> e = map.entrySet().iterator().next();
      K k = e.getKey();
      V v = e.getValue();
      if (checkNulls) {
        Objects.requireNonNull(k, "key");
        Objects.requireNonNull(v, v == null ? "value for key: " + k : null);
      }
      if (skipNulls && (k == null || v == null)) {
        return Collections.emptyMap();
      }
      return Collections.singletonMap(k, v);
    }
    default: {
      Map<K, V> linkedMap = new LinkedHashMap<>(map.size() * 4 / 3 + 1);
      if (skipNulls || checkNulls) {
        for (Map.Entry<? extends K, ? extends V> e : map.entrySet()) {
          K k = e.getKey();
          V v = e.getValue();
          if (skipNulls) {
            if (k == null || v == null) continue;
          } else if (checkNulls) {
            Objects.requireNonNull(k, "key");
            Objects.requireNonNull(v, v == null ? "value for key: " + k : null);
          }
          linkedMap.put(k, v);
        }
      } else {
        linkedMap.putAll(map);
      }
      return Collections.unmodifiableMap(linkedMap);
    }
    }
  }
}
